skip to Main Content

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


  1. 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!) {
    ...
    
    Login or Signup to reply.
  2. 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');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search