createNonNullMap<K, V> function Null safety

Map<K, V?> createNonNullMap<K, V>(
  1. Map<K, V> input,
  2. {bool recursive = true}
)

Returns a new map containing only the entries of input whose value is not null.

If recursive is true, nested maps are also filtered.

Implementation

Map<K, V?> createNonNullMap<K, V>(Map<K, V> input, {bool recursive = true}) {
  final map = <K, V?>{};
  for (final entry in input.entries) {
    if (entry.value != null) {
      map[entry.key] = recursive && entry.value is Map
          ? createNonNullMap(entry.value as Map, recursive: recursive) as V?
          : entry.value;
    }
  }
  return map;
}