Check if an email already exists in Firebase Auth in Flutter App
The error raised is a PlatformException so you can do something as follows-
try {
_firbaseAuth.createUserWithEmailAndPassword(
email: '[email protected]',
password: 'password'
);
} catch(signUpError) {
if(signUpError is PlatformException) {
if(signUpError.code == 'ERROR_EMAIL_ALREADY_IN_USE') {
/// `[email protected]` 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.
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.
There is no such fetchProvidersForEmail
method anymore in the current version of the firebase auth package. The equivalent one is now fetchSignInMethodsForEmail
method which I think would be the best option to handle this case without executing any unnecessary operation.
fetchSignInMethodsForEmail
In docs, it's stated that this method returns an empty list when no user found, meaning that no account holds the specified email address:
Returns a list of sign-in methods that can be used to sign in a given user (identified by its main email address).
This method is useful when you support multiple authentication mechanisms if you want to implement an email-first authentication flow.
An empty List is returned if the user could not be found.
Based on this, we could create our own method like the following one:
// Returns true if email address is in use.
Future<bool> checkIfEmailInUse(String emailAddress) async {
try {
// Fetch sign-in methods for the email address
final list = await FirebaseAuth.instance.fetchSignInMethodsForEmail(emailAddress);
// In case list is not empty
if (list.isNotEmpty) {
// Return true because there is an existing
// user using the email address
return true;
} else {
// Return false because email adress is not in use
return false;
}
} catch (error) {
// Handle error
// ...
return true;
}
}