Home > Blockchain >  The body might complete normally, causing 'null' to be returned, but the return type, 
The body might complete normally, causing 'null' to be returned, but the return type, 

Time:12-08

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');
      }
    }
  }

CodePudding user response:

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 await FirebaseAuth as

 UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: _email, password: _password)

and then check if user returned is null by using an if statement, then continue with the above Firestore part.

Easier way, add nullcheck here:

...
.then((userCredential!) {
...

CodePudding user response:

This happened because you use ! on userCredential which may be null, You can change your code to this:

try {
  UserCredential? userCredential = await FirebaseAuth.instance
      .createUserWithEmailAndPassword(email: _email, password: _password);
  if (userCredential != null) {
    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');
}
  • Related