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();
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();
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]
}
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;
}
}
}