Home > Software design >  Flutter Firebase Authentication and/or Login is not Successful
Flutter Firebase Authentication and/or Login is not Successful

Time:12-12

Firebase Authentication: email/Password was already set to Enabled. Realtime Database: users records exist. Email and Password: thoroughly checked and verified correct.

below are the code for this issue;

final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  void loginAndAuthenticateUser(BuildContext context) async
  {
    final User? firebaseUser = (await _firebaseAuth
        .signInWithEmailAndPassword(
        email: emailTextEditingController.text,
        password: passwordTextEditingController.text
    ).catchError((errMsg){
      displayToastMessage("Error: "   errMsg.toString(), context);
    })).user;

    if(firebaseUser !=null)
    {
      userRef.child(firebaseUser.uid).once().then((value) => (DataSnapshot snap){
        if(snap.value != null){
          Navigator.pushNamedAndRemoveUntil(context, MainScreen.idScreen, (route) => false);
          displayToastMessage("Login successful", context);
        }else{
          _firebaseAuth.signOut();
          displayToastMessage("No records exist. Please create new account", context);
        }
      });
    }else{
      displayToastMessage("Error: Cannot be signed in", context);
    }
}

CodePudding user response:

Try to use await with catch/try, instead of mixing with the .then/.catchError syntax (I don't know what's exactly in userRef, depending on it the database query might need to be adjusted):

try {
  UserCredential userCredential = await _firebaseAuth
    .signInWithEmailAndPassword(
      email: emailTextEditingController.text,
      password: passwordTextEditingController.text);
  final User? firebaseUser = userCredential.user;
  if (firebaseUser != null) {
    final DatabaseEvent event = await 
      userRef.child(firebaseUser.uid).once();
    if (event.snapshot.value != null) {
      Navigator.pushNamedAndRemoveUntil(context, MainScreen.idScreen, 
        (route) => false);
      displayToastMessage("Login successful", context);
    } else {
      displayToastMessage("No records exist. Please create new account", 
        context);
      await _firebaseAuth.signOut();
    }
  } else {
    displayToastMessage("Error: Cannot be signed in", context);
  }
} catch(e) {
  // handle error
}

  • Related