Home > Enterprise >  Flutter firebase authentication error crashing my app
Flutter firebase authentication error crashing my app

Time:02-04

signInsignUpButtons(context, true, () {
  try {
    FirebaseAuth.instance
        .signInWithEmailAndPassword(
            email: _emailTextController.text,
            password: _passwordTextController.text)
        .then((value) {
      Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => homescreenPage(),
          ));
    }); 
  } on FirebaseAuthException catch (error) {
    print(error.message);
    Fluttertoast.showToast(
        msg: error.message.toString(), gravity: ToastGravity.TOP);
  }
  // using firebase api checks whether email and password is correct registered
}),

I'm trying to show authentication errors from firebase such as incorrect password/email (when the user presses the sign in button). Instead of printing the error and displaying a pop up message on the app, it just freezes.

Ive tried using this line which is without fluttertoast

FirebaseAuth.instance
  .signInWithEmailAndPassword(
    email: _emailTextController.text,
    password: _passwordTextController.text)
  .then((value) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => homescreenPage(),
      )).onError((error, stackTrace) {
      print("Error ${error.tostring()}");
    })
  })

But then again, it just doesn't print the error and my app freezes.

Im using these dependancies:

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  firebase_core: ^2.4.1
  firebase_auth: ^4.2.5
  fluttertoast: ^8.1.2

CodePudding user response:

Since signInWithEmailAndPassword is a future, you should use an async function and await in the try-catch block. Something like this should work:

void _signIn() async {
  try {
    await FirebaseAuth.instance.signInWithEmailAndPassword(
      email: <email>,
      password: <password>,
    );
  } on FirebaseAuthException catch (e) {
    // catch FirebaseAuthException errors here
  } catch (e) {
    // catch other exceptions, for example no network
  }
}
  • Related