I’m getting The operator ‘[]’ isn’t defined for the type ‘Object’ on my element![‘id’].
Code:
await Future.forEach(tempList, (element) async {
if (element!['id'] == alertId) {
alertList!.add(element);
screenTitle = element!['subject'] ;
}
});
How to fix this?
Thanks.
>Solution :
You need to check the type of element before accessing it with []. It seems that it’s not a map like it is supposed to be.
Moreover it’s seems like you’re using null check operator ("!") on a value that can be null. It is a good pratice to ensure that your value is not null before acessing it.
To correct that you can do it like this.
await Future.forEach(tempList, (element) async {
if(element != null && element is Map<String,dynamic>){
if (element!['id'] == alertId) {
alertList!.add(element);
screenTitle = element!['subject'] ;
}
}
});
I advise you to type your variables to be aware of what type you’re using for each variable and avoid this kind of error.