0

Is there a more elegant way of removing nulls from a Dart list than this:

List<T> nullFilter<T>(List<T?> list) =>
   list.where((T? e) => e != null)
     // This should not be necessary
   .map((e) => e!)
   .toList();
adko
  • 1,113
  • 2
  • 7
  • 7

2 Answers2

1

Something like this makes it a bit more clean:

List<T> nullFilter<T>(List<T?> list) => [...list.whereType<T>()];

void main() {
  final list1 = [1, 2, 3, null];
  print('${list1.runtimeType}: $list1');
  // List<int?>: [1, 2, 3, null]

  final list2 = nullFilter(list1);
  print('${list2.runtimeType}: $list2');
  // List<int>: [1, 2, 3]
}
julemand101
  • 28,470
  • 5
  • 52
  • 48
1

You could use the very popular collection package (which is an official core package published by the Dart Team) as such:

final list2 = list1.whereNotNull();

Or as pointed out by the comment, if you don't want it as an iterable:

final list2 = list1.whereNotNull().toList();

For reference, the implementation for that is as follows (if you for some reason don't want to include the package but create the extension yourself in your own file):

/// Extensions that apply to iterables with a nullable element type.
extension IterableNullableExtension<T extends Object> on Iterable<T?> {
  /// The non-`null` elements of this `Iterable`.
  ///
  /// Returns an iterable which emits all the non-`null` elements
  /// of this iterable, in their original iteration order.
  ///
  /// For an `Iterable<X?>`, this method is equivalent to `.whereType<X>()`.
  Iterable<T> whereNotNull() sync* {
    for (var element in this) {
      if (element != null) yield element;
    }
  }
}
Robert Sandberg
  • 6,832
  • 2
  • 12
  • 30
  • Note it does return an `Iterable`. So your example `var list2 = list1.whereNotNull();` should remember to convert it to a list before saving it into the variable. :) – julemand101 Nov 14 '22 at 12:42