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 :

Remove null key pair

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

Create Map from map

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

More about Map.

Leave a Reply