TypeError: Cannot read property 'uid' of null flutter

Issue

I’m currently facing this error message at login, my registration function works fine. but can’t seem to figure out why my login keeps bringing this error. I would appreciate if I can be pointed to where my mistake is coming from.

void loginUser() async {
    User user;
    await _auth
        .signInWithEmailAndPassword(email: email.text, password: password.text)
        .then((value) {
      setState(() {
        loading = false;
      });
      return value;
    }).catchError((error) {
      Navigator.pop(context);
      Get.defaultDialog(title: 'Error in Login');
    });
    if (user != null) {
      readData(user).then((value) => Get.toNamed(homeRoute));
    }
  }

  Future readData(User user) async {
    FirebaseFirestore.instance
        .collection('users')
        .doc(user.uid)
        .get()
        .then((result) async {
      await App.sharedPreferences.setString('uid', result.get('uid'));
      await App.sharedPreferences.setString('email', result.get('email'));
      await App.sharedPreferences.setString('fullname', result.get('fullname'));
      await App.sharedPreferences.setString('bvn', result.get('bvn'));
    });
  }

Here’s my Registration function

 void _registerUser() async {
    User user;
    await _auth
        .createUserWithEmailAndPassword(
            email: email.text, password: password.text)
        .then((value) {
      user = value.user;
    }).catchError((error) {
      Navigator.pop(context);
      Get.defaultDialog(title: 'Error in registration');
    });
    if (user != null) {
      saveToFirestore(user).then((value) => Get.toNamed(homeRoute));
    }
  }

  Future saveToFirestore(User user) async {
    FirebaseFirestore.instance.collection('users').doc(user.uid).set({
      'uid': user.uid,
      'fullname': fullname.text.trim(),
      'email': user.email,
      'bvn': bvn.text
    });

    await App.sharedPreferences.setString('uid', user.uid);
    await App.sharedPreferences.setString('email', user.email);
    await App.sharedPreferences.setString('fullname', fullname.text);
    await App.sharedPreferences.setString('bvn', bvn.text);
  }

Solution

Change

  User user;
    await _auth

to User user = await _auth....

And in your FireStore query, use

 Future readData(User user) async {
   FirebaseFirestore.instance
      .collection('users') 
      .doc(user.user.uid) // instead of user.uid
      .get()

Everywhere with user.uid change it to user.user.uid.

Answered By – Huthaifa Muayyad

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *