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

The method 'add' can't be unconditionally invoked because the receiver can be 'null'

I’m trying to handle some data for a flutter application, however I am getting the following error on my code:
The method 'add' 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 ('!').

Map<String, List<SourcefulListing>> sortedSkills = {};
    QuerySnapshot listingSnapshot = await listingsRef.get();
    List<SourcefulListing> listings = [];
    for (int i = 0; i < listingSnapshot.docs.length; i++) {
      listings.add(SourcefulListing.fromJson(
          listingSnapshot.docs[i].data() as Map<String, dynamic>));
    }
    for (String skill in skills) {
      for (SourcefulListing listing in listings) {
        if (listing.selectedSkill == skill) {
          if (sortedSkills[skill] == null || sortedSkills[skill] != []) {
            sortedSkills[skill] = [listing];
          } else {
            sortedSkills[skill] = sortedSkills[skill].add(listing);
          }
        }
      }
    }

Basically I have a Map with Strings as key and List for the values. The for each loop should add the SourcefulListing object to the map, however there is an error on the .add method.
Any help would be much appreciated.

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 :

Try this,

  Map<String, List<SourcefulListing>> sortedSkills = {};
QuerySnapshot listingSnapshot = await listingsRef.get();
List<SourcefulListing> listings = [];
for (int i = 0; i < listingSnapshot.docs.length; i++) {
  listings.add(SourcefulListing.fromJson(
      listingSnapshot.docs[i].data() as Map<String, dynamic>));
}
for (String skill in skills) {
  for (SourcefulListing listing in listings) {
    if (listing.selectedSkill == skill) {
      if (sortedSkills[skill] == null || sortedSkills[skill] != []) {
        sortedSkills[skill] = [listing];
      } else {
        sortedSkills[skill]?.add(listing); // changes made here
         setState(() {}); // update ui
      }
    }
  }
}

Null Safety : https://dart.dev/null-safety

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