简体   繁体   中英

Check if the user is logged in Flutter & firebase auth |

我正在使用 Firebase 身份验证在我的 Flutter 应用程序中对用户进行身份验证,当用户输入正确的密码时,应用程序会正常显示主页但是当密码错误时没有发生任何事情,我想每次显示警报用户输入了错误的密码,我该怎么办?

Use the currentUser() method:

if (await FirebaseAuth.instance.currentUser() != null) {
    // signed in
} else {

}

That didn't work for me so this is what I did:

FirebaseAuth.instance.currentUser().then((firebaseUser){
  if(firebaseUser == null)
   {
     //signed out
   }
   else{
    //signed in
  }
});

try this, it worked for me.

Get token from user and refresh it.

Future<bool> isUserLogged() async {
    FirebaseUser firebaseUser = await getLoggedFirebaseUser();
    if (firebaseUser != null) {
        IdTokenResult tokenResult = await firebaseUser.getIdToken(refresh: true);
        return tokenResult.token != null;
    } else {
        return false;
    }
}

Future<FirebaseUser> getLoggedFirebaseUser() {
    return firebaseAuthInstance().currentUser();
}

Maybe the shortest and safest answer is:

if(FirebaseAuth.instance.currentUser?.uid == null){
// not logged
} else {
// logged
}

It gets the User ID (if exists) which is recorded on Firebase Authentication UID field for each user have been authenticated on the app before, otherwise it returns null.
The question mark in currentUser?.uid is a Null safety to avoid null exception (returns null if null).

if (FirebaseAuth.instance.currentUser() != null) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Home(),
    );
} else {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Welcome(),
    );
}

void _emailLogin() async{ final user = await _auth.signInWithEmailAndPassword(email: email, password: password);

    if(user != null){
     // Do something
    }
  } catch (e) {

    String exception = Auth.getExceptionText(e);
    Flushbar(
      title: "Sign In Error",
      message: exception,
      duration: Duration(seconds: 5),
    )..show(context);

  }

In Your Init Method Do This..

 FirebaseAuth.instance.currentUser().then((firebaseUser) {
    if (firebaseUser == null) {
     
      Navigator.pushReplacement(
          context,
          MaterialPageRoute(
              builder: (BuildContext context) => LoginPage()));
    } else {
      Navigator.pushReplacement(context,
          MaterialPageRoute(builder: (BuildContext context) => HomePage()));
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM