LateInitializationError: Field ‘[email protected]’ has not been initialized

Total
0
Shares

Getting this when trying to initialize data.

The following LateError was thrown building UserProfile(dirty, state: _UserProfileState#752a9):
LateInitializationError: Field ‘[email protected]’ has not been initialized."

Here’s the code:

    late final User _user;
    late final DocumentSnapshot _userData;
    
      @override
      void initState() {  
        super.initState();
        _initUser();
      }
    
      void _initUser() async {
        _user = FirebaseAuth.instance.currentUser!;
        try {
          _userData = await FirebaseFirestore.instance
              .collection('users')
              .doc(_user.uid)
              .get();
        } catch (e) {
          print("something went wrong");
        }
      }

The build function is not even running as i tried to print _user and _userData to check if they have been initialized.
If i try to print _user and _userData in initUser() function, _user gets printed and _userData gets printed after the error statements.
Please help me find a way out through this error.


Solution

Even though you are initializing these variables inside the initUser(), but you will get this error if you are using the variables inside the build() method since initUser() is asynchronous meaning it will take time to get the data from the collection. To solve this you can do:

@override
      void initState() {  
        super.initState();
        _initUser().whenComplete((){
          setState(() {});
       });
      }

This will rebuild the widget tree with the new values.

Source: StackOverflow.com

Leave a Reply

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