Home > Software engineering >  How can I remove the mapEntry with the value is null and correct the type?
How can I remove the mapEntry with the value is null and correct the type?

Time:05-17

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?

CodePudding user response:

Remove null key pair

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

Create Map from map

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

More about Map.

CodePudding user response:

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

CodePudding user response:

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}
  • Related