'Flutter + Firestore error: The method '[]' can't be unconditionally invoked because the receiver can be 'null'

The following code throws this error "The method '[]' can't be unconditionally invoked because the receiver can be 'null'"

if (snapshot.hasData == true) {
          return ListView(
            children: snapshot.data!.docs.map((DocumentSnapshot document) {
                return ListTile(
                  title:  Text(document.data()['title']),
                );
            }).toList(),
          );
        }

Is it related to null-safety? how to fix it?



Solution 1:[1]

Try doc.get('title')

instead of document.data()['title']

Solution 2:[2]

you can also cast values with dynamic like:

(document.data()['title'] && document.data() as dynamic)['title']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sungkd123
Solution 2 Paresh Mangukiya