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.

>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

Leave a Reply