'How can I remove the mapEntry with the value is null and correct the type?

For the case of nullable variable, I can use whereType to remove the null value in a list:

List<String?> myList = [null, '123'];
List<String> updatedList = List.from(myList.whereType<String>());
print(updatedList);

// get [123]

But when it comes to Map, it cannot work as expected:

Map<String, String?> myMap = {'a':'123', 'b': null};
Map<String, String> updatedMap = Map.fromEntries(myMap.entries.whereType<MapEntry<String,String>>());
print(updatedMap);

// get {}

I can only think of a workaround method by wrapping it with another function with a for-loop, adding the result and return. It does not sound elegant at all. Can someone suggest how to handle th case?



Solution 1:[1]

Remove null key pair

 myMap.removeWhere((key, value) => value == null);

Create Map from map

Map<String, String> updatedMap = Map.from(myMap);

More about Map.

Solution 2:[2]

You may try this, using where to filter null and map to convert <String, String?> to <String, String>.

ps: you can't use as ...<String, String> that why need map.

void main() {
  Map<String, String?> myMap = {'a':'123', 'b': null};
  // Map<String, String> updatedMap = Map.fromEntries(myMap.entries.whereType<MapEntry<String,String>>());
  Map<String, String> updatedMap = Map.fromEntries(myMap.entries.where((e) => e.value != null).map((e) => MapEntry(e.key, e.value!)));
  print(updatedMap);
  print(updatedMap.runtimeType);
  
  // result
  // {a: 123}
  // JsLinkedHashMap<String, String>
}

Solution 3:[3]

void main(List<String> args) {
  var myMap = {'a':'123', 'b': null};
  print(myMap);
  myMap.removeWhere((key, value) => value == null);
  print(myMap);
}

Output:

{a: 123, b: null}
{a: 123}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yeasin Sheikh
Solution 2 Tuan
Solution 3 Ουιλιαμ Αρκευα