firebaseflutterfirebase-authentication

Error: Property 'uid' cannot be accessed on 'User?' because it is potentially null


Hi new to flutter and firebase what i am tried to make is simple signup new user then add it's information to cloud firestore with custom id and adding subcollections names "notifications" here sample of the code ..

final _auth = FirebaseAuth.instance;
  final _ref = FirebaseFirestore.instance;
  final userCollections = FirebaseFirestore.instance.collection("users");
  Future<void> SignupToColud(
      {@required String name = "",
      @required String email = "",
      @required String pass = ""}) async {
    try {
      await _auth
          .createUserWithEmailAndPassword(email: email, password: pass)
          .then((value) {
        String userId = value.user.uid;
        if (userId != null) {
          userCollections.doc(userId).set({'name': name, 'email': email});
          userCollections
              .doc(userId)
              .collection("notifications")
              .add({'txt': 'welcome you registered as new user succefully'});
        } else {
          throw Error();
        }
      });
      // first sign up to cloud if success

      //then add to users collections
    } catch (e) {
      print(e.toString());
    }
  }

i got this error !!

    lib/Sign_up.dart:24:36: Error: Property 'uid' cannot be accessed on 'User?' because it is potentially null.
 - 'User' is from 'package:firebase_auth/firebase_auth.dart' ('/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_auth-1.2.0/lib/firebase_auth.dart').
Try accessing using ?. instead.
        String userId = value.user.uid;
                               ^^^

this is pubspec.yaml file information environment: sdk: ">=2.12.0 <3.0.0"

dependencies:

  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.0
  firebase_core: ^1.2.0
  cloud_functions: ^1.1.0
  cloud_firestore: ^2.2.0
  firebase_storage: ^8.1.0
  firebase_auth: ^1.2.0

i really have no idea with the problem and how to solve it :(


Solution

  • The error comes from this line:

    String userId = value.user.uid;
    

    As the error says value.user is a User?, meaning that it can either be a User object or it can be null. Your code needs to handle this fact that is can be null, as only you can decide what do do in that case.

    I think what you want it:

      _auth
          .createUserWithEmailAndPassword(email: email, password: pass)
          .then((value) {
        if (value.user != null) {
          String userId = value.user!.uid;
          userCollections.doc(userId).set({'name': name, 'email': email});
    

    So this checks if value.user is null (instead of checking for the userId. If value.user is not null, the uid is guaranteed to have a value, so we can use that in the write operation.