Home > Mobile >  How to return a exception message to the user in dart?
How to return a exception message to the user in dart?

Time:12-20

is it possible to return an exception message back to the user? If Yes, how may i achieve it? I want to let the user know the exception message returned whenever occured. Plus, i don't want my app to crash at the time when the exception occurs.

To be more specific, i want to return the error message back to the user while the user is trying to login. I have used Firebase as my auth provider.

I have inlcuded my code below for a better understanding.

Thank you in advance.

 Future<User?> signInWithEmailAndPassword(
    String email,
    String password,
  ) async {
    try {
      final credential = await _firebaseAuth.signInWithEmailAndPassword(
          email: email, password: password);
      return _userFromFirebase(credential.user);

      throw Exception('Some Error occured. ');
    } on auth.FirebaseAuthException catch (e, _) {
      print(e);

    } catch (e) {
      print(e);
    }
  }

CodePudding user response:

You can show an error message using ScaffoldMessenger to the user

   Future<User?> signInWithEmailAndPassword(
    BuildContext context,
    String email,
    String password,
  ) async {
    try {
      final credential = await _firebaseAuth.signInWithEmailAndPassword(
          email: email, password: password);
      return _userFromFirebase(credential.user);
      
      throw Exception('Some Error occured. ');
      
    } on auth.FirebaseAuthException catch (e, _) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(e.toString()),
    ));
    } catch (e) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(e.toString()),
    ));
    }
  }
  • Related