Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading