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?
myMap.removeWhere((key, value) => value == null);
Map<String, String> updatedMap = Map.from(myMap);
More about Map
.