toNonNullMap<K, V> function

Map<K, V> toNonNullMap<K, V>(
  1. Map? map, {
  2. bool forceTypeCast = true,
})

Converts map to a Map<K,V> ignoring any entry with null key or null value.

  • forceTypeCast: if true, will try to cast key as K and values as V. if false, will ignore any entry that can't be cast.

Implementation

Map<K, V> toNonNullMap<K, V>(Map? map, {bool forceTypeCast = true}) {
  if (map == null || map.isEmpty) {
    return <K, V>{};
  }

  Iterable<MapEntry<K, V>> entries;

  if (forceTypeCast) {
    entries = map.entries
        .where((e) => e.key != null && e.value != null)
        .map((e) => MapEntry(e.key! as K, e.value! as V));
  } else {
    entries = map.entries
        .where((e) => e.key is K && e.value is V)
        .map((e) => MapEntry(e.key! as K, e.value! as V));
  }

  var map2 = Map<K, V>.fromEntries(entries);
  return map2;
}