I created a view model for sign up and in there are my validators.
String? emailValidator(String? s) {
if(s == null || s.isEmpty || s.isWhiteSpace()){
return "Email is required";
}
if(!s.isValidEmail()){
return "Invalid email address";
}
return null;
}
When I create an account I call createUserWithEmailAndPassword but when the user already exists this throws an exception.
onPressed: () {
final isValid = formKey.currentState!.validate();
assert(isValid == viewModel.isValid(),
"The view model and form must agree on whether the form is valid");
if(isValid && viewModel.isValid()){
try{
FirebaseAuth.instance.createUserWithEmailAndPassword(email: viewModel.email!, password: viewModel.password!);
}catch{
// what should I do here?
}
}
},
Now I want to catch it and update my validator so that i can display an error like "email address already in use". How can I do this?
2
Answers
Create a bool
and on button press in catch you can update the bool and validate again
Since you to use
try
/catch
, the syntax for handling exception is:You likely only need the first
catch
block which handlesFirebaseAuthException
s, and in there you can usee.code
to determine the actual error code from Firebase. For the actual codes, see what are the error codes for Flutter Firebase Auth Exception?We did an episode of the Flutter Boring Show on this topic a while ago, so I recommend checking that out: Firebase Authentication in Flutter (The Boring Flutter Development Show, Ep. 55), also see the final code of what we created there.