skip to Main Content

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.

2

Answers


  1. Is your ‘tempList’ a List or a Map?
    In case it is a List the way of calling a var named ‘id’ is element[index].id

    By the way, be careful about using "!" without checking if the value indeed is not null, it might throw an "Null check operator used on a null value" exception.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search