问题
I'm currently developing a flutter app that requires users to register before using it. I use Firebase Authentication and would like to check whether an email is already registered in the app.
I know the easy way to do it is to catch the exception when using the createUserWithEmailAndPassword()
method (as answered in this question). The problem is that I ask for the email address in a different route from where the user is registered, so waiting until this method is called is not a good option for me.
I think the best option would be to use the method fetchProvidersForEmail()
, but I can't seem to make it work.
How do I use that method? Or is there a better option to know if an email is already registered?
回答1:
I think the only possibility from within the app is attempting a login (signInWithEmailAndPassword
) with that e-mail and check the result.
If it's invalid password, the account exists. If it's invalid account, the account do not exist.
Error 17011
There is no user record corresponding to this identifier. The user may have been deleted
Error 17009
The password is invalid or the user does not have a password
As this is a kind of an ugly solution, you can justify this additional call using it to check it the e-mail formatting is correct (according to the firebase rules). If it doesn't comply it will throw a address is badly formatted
and you can alert the user soon enough.
You can do these checks using the error codes with current versions of the plug-in.
回答2:
The error raised is a PlatformException so you can do something as follows-
try {
_firbaseAuth.createUserWithEmailAndPassword(
email: 'foo@bar.com',
password: 'password'
);
} catch(signUpError) {
if(signUpError is PlatformException) {
if(signUpError.code == 'ERROR_EMAIL_ALREADY_IN_USE') {
/// `foo@bar.com` has alread been registered.
}
}
}
The following error codes are reported by Firebase Auth -
- ERROR_WEAK_PASSWORD - If the password is not strong enough.
- ERROR_INVALID_EMAIL - If the email address is malformed.
- ERROR_EMAIL_ALREADY_IN_USE - If the email is already in use by a different account.
来源:https://stackoverflow.com/questions/51652134/check-if-an-email-already-exists-in-firebase-auth-in-flutter-app