4

I have a two-step Login form where the user enters their email first, then is taken to the next page where they enter their password. Prior to taking the user to the password page, I want to check if the email entered by the user is valid and whether it exists in firebase. I have read a few posts about using fetchSignInMethodsForEmail. However, I'm not quite sure how to implement this.

The idea is if the email does exist the user is taken to the password page, however, if the email does not exist a snackbar pops up with a button taking the user to the register page. How would I go about doing this?

This is what I have so far...

FirebaseAuth auth = FirebaseAuth.instance;


    final nextButton = Container(
      margin: const EdgeInsets.only(
        top: 30.0,
      ),
      child: FloatingActionButton(
        onPressed: () async {
          try {
            List<String> userSignInMethods = await auth.fetchSignInMethodsForEmail(email)(
               email: _emailController.text,
            );
            if (userSignInMethods != null) {
              final page = LoginPassword();
              Navigator.of(context).push(CustomPageRoute(page));
            }
          } catch (e) {
            print(e);
            //TODO: Snackbar 
          }
        },
        tooltip: 'Next',
        backgroundColor: AppTheme.define().primaryColor,
        child: Icon(
          AppIcons.next_button,
          size: 20.0,
        ),
      ),
    );

The fetchSignInMethodsForEmail isn't implemented properly, I'm getting an error.

Joe
  • 263
  • 5
  • 20
  • Handle the error once you catch the exception, because it'll be thrown in the case if email already exists. – dh4ze Mar 15 '21 at 06:35
  • What error do you get? – Siddharth Agrawal Mar 15 '21 at 07:37
  • 3
    Does this answer your question? [Check if an email already exists in Firebase Auth in Flutter App](https://stackoverflow.com/questions/51652134/check-if-an-email-already-exists-in-firebase-auth-in-flutter-app) – MrMikimn Mar 15 '21 at 17:03

3 Answers3

2

For the method fetchSignInMethodsForEmail looking at the documentation, An empty List is returned if the user could not be found. It can't be null since that method returning an empty list, so you can check for the length. userSignInMethods.length > 0

Madhan
  • 305
  • 1
  • 5
  • 10
1

This probably isn't what you are looking for but what I usually do is store the users in a collection in firestore since that allows me to store multiple values for the user like nickname, picture, points etc. If you want some sample code on how to do this, let me know

EDIT

This is some code to help you get started.

First set up the firestore and set up a collection named users. Create a document in it with your mail id and add the fields you want for a user in it. If you do not do this you will get an error that the collection cannot be found or firestore is not set up

While signing up, do something like this given the email is in variable email and password in pass

FirebaseFirestore.instance.collection('users').doc(email).set((){
   "email":email,
   "pass":pass,
   "nick":nick,//You can add more fields or remove them
});

When you want to check if the email exists, do something like

QuerySnapshot query = await FirebaseFirestore.instance.collection('users').where('email',isEqualTo:email).get();
if (query.docs.length==0){
   //Go to the sign up screen
}
else {
   //Go to the login screen
}

Now to check the password while signing in, do something like

QuerySnapshot query = await FirebaseFirestore.instance.collection('users').where('email',isEqualTo:email).get();//You can also pass this query as a parameter when you push the login screen to save some time
if (query.docs[0].get('pass')==pass){
   //Go ahead login
}
else{
   //Display an error message that password is wrong
}

If you want to store the data to automatically login when the user opens the app next time, look into the Shared Preference library.

If you want to pass the user data around, create a class called User()


class User {
  String email;
  String pass;
  String nick;

  User(this.email,this.nick,this.pass);
}

Then you can pass it around and easily manage the user data

Siddharth Agrawal
  • 2,960
  • 3
  • 16
  • 37
0

You can try catch and exception like as my code. And let me know.

try {
  _firbaseAuth.createUserWithEmailAndPassword(
    email: 'ab@gmail.com', 
    password: '123456'
  );
} catch(signUpError) {
  if(signUpError is PlatformException) {
    if(signUpError.code == 'ERROR_EMAIL_ALREADY_IN_USE') {
      /// ab@gmail.com has alread been registered.
    }
  }
}
Harsh Chovatiya
  • 295
  • 2
  • 6
  • This is a good idea! However I added print("test") in the if statement where you wrote foo@bar.com. nothing was printing. However the terminal was saying that the email already exists. I'm not sure what's wrong here – Joe Mar 15 '21 at 07:17
  • This should be comment rather, which you basically copy/pasted code from another SOF question. – dh4ze Mar 15 '21 at 07:51