flutterfirebasedartexceptionfirebase-authentication

Flutter firebase exception not being caught by try-catch block


I am trying to implement simple login using flutter and firebase(just started learning). The user-not-found error is not being caught by the try-catch block in the code.

Code in Question

TextButton(
  onPressed: () async {
    final email = _eMail.text;
    final password = _passWord.text;
    try {
      final userCredential =
          FirebaseAuth.instance.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
      print(" UC = \n");
      print(userCredential);
    } catch (e) {
      print("Error Code: ");
      print(e.runtimeType);
      print(e);
    }
  },
  child: Text("Login"),
),

Output(in the debugger):

I/flutter (10795):  UC = 
I/FirebaseAuth(10795): Logging in as nvnv@gmail.com with empty reCAPTCHA token
I/flutter (10795): Instance of 'Future<UserCredential>'
W/System  (10795): Ignoring header X-Firebase-Locale because its value was null.
E/RecaptchaCallWrapper(10795): Initial task failed for action RecaptchaAction(action=signInWithPassword)with exception - There is no user record corresponding to this identifier. The user may have been deleted.
E/flutter (10795): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_auth/user-not-found] There is no user record corresponding to this identifier. The user may have been deleted.
E/flutter (10795): #0      FirebaseAuthHostApi.signInWithEmailAndPassword (package:firebase_auth_platform_interface/src/pigeon/messages.pigeon.dart:1158:7)
E/flutter (10795): <asynchronous suspension>
E/flutter (10795): #1      MethodChannelFirebaseAuth.signInWithEmailAndPassword (package:firebase_auth_platform_interface/src/method_channel/method_channel_firebase_auth.dart:343:22)
E/flutter (10795): <asynchronous suspension>
E/flutter (10795): #2      FirebaseAuth.signInWithEmailAndPassword (package:firebase_auth/src/firebase_auth.dart:590:9)
E/flutter (10795): <asynchronous suspension>
E/flutter (10795):

From what I understand, if the error was caught, the print(" UC = \n"); statement should not have been executed.

Please help me solve this problem


Solution

  • As DanR commented, the signInWithEmailAndPassword method is asynchronous, so you have to use await to wait for it to complete:

    //                      👇
    final userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
      email: email,
      password: password,
    );