skip to Main Content

How do I check if a List of Maps List<Map<String, List<CustomObject>>> listOfMaps does not contain a specific key?

I am looping through listOfMaps and checking if a map contains a specific key.

If so I write over the values (code below):

listOfMaps.forEach((map) {
      if (map.containsKey(key)) {
        // write over values...
      }
    });

However if the listOfMaps does not contain the key I want to add the new map to the list:

listOfMaps.add(
        {key: [
      // Custom Objects
    ]}
    );

How do I check if listOfMaps does not contain a specific key?

*Edit:

listOfMaps = [
{'map1': [listOfCustomObjects]},
{'map2': [listOfCustomObjects]},
{'map3': [listOfCustomObjects]},
]

I am now dealing with new data:
{'map4': [listOfCustomObjects]}

if listOfMaps doesn’t contain key ‘map4’ I want to add a map, if listOfMaps does contain ‘map4’ already I want to write over the values.

2

Answers


  1. Chosen as BEST ANSWER

    A solution that I came up with... If anybody has a simpler way of doing it let me know...

      checkIfListOfMapsContainsKey({
        required String key,
        required List<Map<String, List<CustomObject>>> listOfMaps,
      }) {
        bool hasKey = false;
        listOfMaps.forEach((map) {
          if (map.containsKey(key)) {
            hasKey = true;
          }
        });
        return hasKey;
      }
    

    then:

    bool hasKey = checkIfListOfMapsContainsKey(
              key: key,
              listOfMaps: listOfMaps,
            );
            if (hasKey == false) {
              listOfMaps.add({'map4': [listOfObjects]});
              
            }
    

  2. Simple enough.

    listOfMaps.update('map4', (old) => (old with new), ifAbsent: () => new); 
    

    EDIT: ooops. That’s not the problem to be solved. I’ll just leave this here because people forget this works for some problems. {sigh}

    I’d also suggest that the ordering of the maps is likely insignificant, so this should really just be a map with keys, not a list of maps with a single key, and then my solution is applicable.

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