1

I am trying to initialize fields from a FirebaseFirestore document using GetXcontroller but I am getting the following error:

Unhandled Exception: Null check operator used on a null value.

The Controller gets created but it doesn't get initialized because of the null check operator used on null value. Here's my code:

class DataController extends GetxController{
  DocumentSnapshot? userDocument;
  FirebaseAuth auth = FirebaseAuth.instance;

  getUserProfileData() {
    FirebaseFirestore.instance
        .collection('users')
        .doc(auth.currentUser!.uid) //Null check operator used on a null value
        .snapshots()
        .listen((event) {
      userDocument = event;
    });
  }

  @override
  void onInit() {
    super.onInit();
    getUserProfileData();
  }
}

My error log:

E/flutter (11591): #1      DataController.onInit
data_controller.dart:76
E/flutter (11591): #2      GetLifeCycleBase._onStart
lifecycle.dart:66
E/flutter (11591): #3      InternalFinalCallback.call
lifecycle.dart:12
E/flutter (11591): #4      GetInstance._startController
get_instance.dart:253
E/flutter (11591): #5      GetInstance._initDependencies
get_instance.dart:204
E/flutter (11591): #6      GetInstance.find
get_instance.dart:301
E/flutter (11591): #7      GetInstance.put
get_instance.dart:86
E/flutter (11591): #8      Inst.put
extension_instance.dart:89
E/flutter (11591): #9      main
main.dart:23
E/flutter (11591): <asynchronous suspension>
E/flutter (11591):
jraufeisen
  • 3,005
  • 7
  • 27
  • 43
Anesu Mazvimavi
  • 131
  • 1
  • 9
  • Does this answer your question? [Null check operator used on a null value](https://stackoverflow.com/questions/64278595/null-check-operator-used-on-a-null-value) – Ken White Feb 18 '23 at 13:28

1 Answers1

1

The error tells you that in this expression

auth.currentUser!.uid

the value of currentUser is null. This means that the user is not authenticated at that point. Make sure to perform user login before reaching this point of your code. As a safeguard you should also manually check if the user is authenticated before calling this chain. For example via

if (auth.currentUser != null) {
    FirebaseFirestore.instance
        .collection('users')
        .doc(auth.currentUser!.uid) //Force unwrapping is now fine here
        // ...
}
jraufeisen
  • 3,005
  • 7
  • 27
  • 43