the property 'uid' cant be unconditionally accessed because the receiver can be null

224 Views Asked by At

i am trying to return value in users where i am getting this error if i am trying to fix this error by adding null sign it does not return any value becuase all this value is going to be null and i want to return this value and save it so i can use it what can be the solution Please guide

FirebaseAuth auth = FirebaseAuth.instance;
User? user = FirebaseAuth.instance.currentUser;
CollectionReference users = FirebaseFirestore.instance.collection('users');

Future<void> addUser(context) {
  //before we add user we need to check this user already signedin earlier using same number or not
  //if signedIn before no need to add , because it may have added already. so just need to skip adduser




  return users
      .add({
    'uid': user.uid,
    'mobile':  user.phoneNumber,
    'email': user.email
  })
      .then((value){
        //after add data to firebase then will go to next screen
    //if you pushreplacementName or push replacement, then u cant go back to previous screen
    Navigator.pushReplacementNamed(context, LocationScreen.id);

  })
      .catchError((error) => print("Failed to add user: $error"));
}
1

There are 1 best solutions below

3
On

that is because uid is nullable. try this

 return users
      .add({
    'uid': user.uid ?? "default username"
    'mobile':  user.phoneNumber,
    'email': user.email
  })

default username will be saved in firestore if uid is null.