· Flutter, it becomes interesting ;-)

Manage errors authentication in Firebase

Hi,
A little tutorial about Firebase authentication by email/password. I was looking for a solution that allows to display errors when trying to authenticate different from the one used with the 'Authentication > Log in' function.

So I created a new custom function that allows to log in if all credentials are correct or to return a custom error that can be displayed in a bottom view for example!

1- Go to Custom Action
2- Click on "+ Create
3- Give a name to your code, I chose "authFlutterFire".
4- Activate "Return value" and in "Data Type", select "String".



5- In "Define Arguments", click on "+ Add Parameter" then give an for Argument Name "emailAdress" and select the "Data Type" in our case here "String"

6 - Click on "+ Add Parameter" then give an for Argument Name "password" and select the "Data Type" in our case here "String"

7 - Click on "+ Add Parameter" then give an for Argument Name "messageInvalidEmail" and select the "Data Type" in our case here "String"

8 - Click on "+ Add Parameter" then give an for Argument Name "messageWrongPassword" and select the "Data Type" in our case here "String"

9 - Click on "+ Add Parameter" then give an for Argument Name "messageUserNotFound" and select the "Data Type" in our case here "String"







10- Click on "+ Add Dependency" then enter "firebase_auth".



11- On the right side, enter the following code:

import 'package:firebase_auth/firebase_auth.dart';

Future<String> authFlutterFire(
  String emailAddress,
  String password,
  String messageInvalidEmail,
  String messageWrongPassword,
  String messageUserNotFound,
) async {
  String returnAuth = "valid";
  try {
    await FirebaseAuth.instance
        .signInWithEmailAndPassword(email: emailAddress, password: password);
  } on FirebaseAuthException catch (e) {
    // POSSIBLE ERRORS
    //
    // invalid-email
    // wrong-password
    // user-not-found
    //
    switch (e.code) {
      case 'invalid-email':
        returnAuth = messageInvalidEmail;
        break;
      case 'wrong-password':
        returnAuth = messageWrongPassword;
        break;
      case 'user-not-found':
        returnAuth = messageUserNotFound;
        break;
    }
  }
  return returnAuth;
}

You should have this screen :




12- Finish by pressing "Check errors", after a few seconds you should get a green button "No Errors!".

You can now use this code in your actions.





I hope you will find it useful. 
Don't hesitate to ask me questions.

Damien

5
15 replies