Reputation: 25
late QuerySnapshot searchSnapshot;`
initiateSearch() {
databaseMethods
.getUserByUsername(searchTextEditingController.text)
.then((val) {
print(val.toString());
setState(() {
searchSnapshot = val;
});
});
}
Widget searchList() {
return searchSnapshot != null ? ListView.builder(
itemCount: searchSnapshot.docs.length,
itemBuilder: (context, index) {
return SearchTile(
userName: searchSnapshot.docs[index].data()["name"], //error here
userEmail: searchSnapshot.docs[index].data()["email"] //error here
);
}): Container();
}
The code shows a red line at .data()["name"],
and .data()["email"]
under [.
The following is the error:
The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').
Upvotes: 0
Views: 92
Reputation: 55
Just use the oparator ?.
like this :
userName: searchSnapshot.docs[index]?.data()["name"],
userEmail: searchSnapshot.docs[index]?.data()["email"]
And it should be fine.
The ?.
oparator makes the call conditional, so in the case data()["name"]
or data()["email"]
is null, it will simply return null
instead of throwing a NullPointerException.
This article might be useful.
Upvotes: 1