How can I resolve “LateInitializationError: Field ‘userMap’ has not been initialized.”

late Map<String,dynamic> userMap;

bool isLoading = false;
final TextEditingController _search = TextEditingController();


void onSearch() async{
FirebaseFirestore _firestore = FirebaseFirestore.instance;
setState(() {
  isLoading = true;
});
await _firestore.collection('users').where('email', isEqualTo: _search.text)
    .get().then((value) {
      setState(() {
        userMap = value.docs[0].data();
        isLoading = false;
      });
      print(userMap);
});

}

This first part of the code work proprely but when I want to create my ListTile the error pop up.

userMap != null ?
        ListTile(
          title: Text(userMap['name']),
          subtitle: Text(userMap['email']),
        ):Container(),

If somoene can help me that’s will be great thank you !

Answer

The late keyword can be used when you have a non-nullable variable, but you just want to initialize it later. The variable will never be null, having only two states, non initialized or initialized with a non-null value.

If you want to work with nullable variables you can only add the ? keyword to the variable like Map<String,dynamic>? userMap;