Reputation: 2792
i just convert my project Null Safety and i am getting error saying
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 ('!').
i am somehow confuse i dont no what to do.
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: snapshot.data['Interest'].length ,// i am getting error here
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(top: 12.0),
child: bottomCardList(
'assets/1 (6).jpeg',
snapshot.data['Interest'][index]// i am getting error here
.toString(),
() {}),
);
});
}),
Thanks
Upvotes: 0
Views: 3218
Reputation: 268504
Problem:
You get this error on retrieving a value from a map of nullable type i.e. Map?
. Say you have:
Map? map;
And you're accessing it
int i = map['0']; // <-- Error
Solutions:
Provide a default value (recommended)
int i = map?['0'] ?? -1;
Use a Bang operator if you are sure that the value is not null
.
int i = map!['0'];
Upvotes: 1
Reputation: 1103
What's happening is that after switching to null safety, you cannot directly write statements using variables that can be null, without checking if they're null. In this case, the variable snapshot.data can be null, so you have to write code accordingly. Try converting your code to this:
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: snapshot.data!['interest'].length,
// i am getting error here
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(top: 12.0),
child: bottomCardList(
'assets/1 (6).jpeg',
snapshot.data?['Interest'][index] // i am getting error here
.toString(),
),
);
},
);
Now, with this, your error for itemCount should vanish (if not, update your cloud_firestore plugin, it's not null safe). As for the error you're getting at bottomCardList, it depends on if your parameters for bottomCardList are null safe. If bottomCardList is of type bottomCardList(String someVar, String someOtherVar), you can change it to bottomCardList(String someVar, String? someOtherVar). Then, inside your bottomCardList code, you have to make sure you are dealing with the case where someOtherVar can be null.
You can check this video out for more information: https://www.youtube.com/watch?v=iYhOU9AuaFs
Edit For the "not defined for object error":
I assume your builder parameter looks something like:
builder: (context, snapshot) {
return ListBuilder etc. etc.
}
Try changing it to:
builder: (context, AsyncSnapshot<DocumentSnapshot<Map<String, dynamic>>> snapshot) {
return ListBuilder etc. etc.
}
and the error should go away. DocumentSnapshot is if you're doing collection.docs.snapshots(). If you're doing collection.snapshots(), use QuerySnapshot etc. etc.
Upvotes: 0
Reputation: 2792
I solved this by giving the StreamBuilder
a type.
StreamBuilder<DocumentSnapshot<Map>>
Upvotes: 1