'The method '[]' was called on null. Receiver: null Tried calling: []("displayName")
This error is caused by what? The other files have the same code format, but there are no errors.
I use displayName as the document name.
Error
The method '[]' was called on null.
Receiver: null
Tried calling: [] ("displayName")
final DocumentSnapshot data;
body: StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection('users')
.document(widget.data['displayName'])
.collection('chat')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return LinearProgressIndicator();
return Container();
})
DB :
static Future<void> sendChatToFirebase(
String chatID,
String chatContent,
FirebaseUser currentUser,
DocumentSnapshot data
) async {
Firestore.instance
.collection('users')
.document(data.documentID)
.collection('chat')
.document(chatID)
.setData({
'chatID': chatID,
'chatTimeStamp': DateTime.now().millisecondsSinceEpoch,
'chatContent': chatContent,
'displayName': currentUser.displayName,
'photoUrl': currentUser.photoUrl,
});
}
Solution 1:[1]
The error message means, that you are trying to access ['displayName'] from a null value. Somehow your widget.data is null.
It's basically the same as calling null['displayName']
Map<String, dynamic> test; // NULL, but expected as Map / Json / {}
print(test["displayName"]); // throws an error, because what was actually called is null["displayName"]
Solution 2:[2]
The index [] operator on the Map class returns null if the key isn’t present. This implies that the return type of that operator must be nullable.
See null safety. This means that your
widget.data['displayName']
may return null.
To fix your issue you need to check that widget.data['displayName] is not null, if so then you can use the ! to say that widget.data['displayName] is not null.
widget.data['displayName']!
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 | Maksim Nikolaev |
| Solution 2 | quoci |
