flutterfirebasegoogle-cloud-firestorefirebase-authentication

Firebase throwing error on FirebaseAuth initialization


FirebaseAuth always throws an error whenever I initialize final uid = FirebaseAuth.instance.currentUser!.uid;.

The error is Null check operator used on a null value.

So I have to use it in a function such as the one below before it works.

FirebaseFirestore.instance.collection("collectionPath") .doc(FirebaseAuth.instance.currentUser!.uid).snapshots();

I don't want to write that long code everytime. What can I do to resolve this?


Solution

  • In the line of the code

    FirebaseAuth.instance.currentUser!.uid;
    

    You are using ! operator which tells the code that uid will never be null. In your case, it seems currentUser is null, because the Authentication was not successful. So you need to check like this

    if(FirebaseAuth.instance.currentUser != null){
     FirebaseAuth.instance.currentUser!.uid;
    }
    

    or

    FirebaseAuth.instance.currentUser?.uid ?? '' // if uid is String 
    

    to understand more about Null Safety best to check Dart documentation