Agnelo Fernandes
Agnelo Fernandes

Reputation: 25

The method '[]' can't be unconditionally invoked because the receiver can be 'null'. I am getting this error in this code

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

Answers (1)

Salomon Diei
Salomon Diei

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

Related Questions