Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm getting a null safety error on Future forEach

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading