I am building a flutter app and I am trying to create a method that will enable users to be registered in Firebase as well as storing their data in Firestore. I am getting an error where the body is returning null. I know the method has to return Usercredential somehow but I am a bit stuck. Please may anyone assist.
Here’s my code:
void validateAndSubmit() async {
if (validateAndSave()) {
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: _email, password: _password)
.then((userCredential) {
FirebaseFirestore.instance.collection('users').doc(userCredential.user!.uid).set({
"uid": userCredential.user!.uid,
'Name': _name,
'userName': _userName,
'email': _email,
});
}
);
Navigator.pushNamed(context, '/home');
print('Registered user: ${userCredential.user}');
const snackBar =
SnackBar(content: Text('User has been successfully registered!'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
} on FirebaseAuthException catch (e) {
print('Error: $e');
}
}
}
2
Answers
This error is due to chances of
userCredential
being null, i.e Firebase not being able to create a user with given credentials. So it’d be better to awaitFirebaseAuth
asand then check if user returned is null by using an
if
statement, then continue with the aboveFirestore
part.Easier way, add nullcheck here:
This happened because you use
!
onuserCredential
which may be null, You can change your code to this: