【发布时间】:2022-11-14 21:13:01
【问题描述】:
有没有比这更优雅的从 Dart 列表中删除空值的方法:
List<T> nullFilter<T>(List<T?> list) =>
list.where((T? e) => e != null)
// This should not be necessary
.map((e) => e!)
.toList();
【问题讨论】:
标签: dart dart-null-safety
有没有比这更优雅的从 Dart 列表中删除空值的方法:
List<T> nullFilter<T>(List<T?> list) =>
list.where((T? e) => e != null)
// This should not be necessary
.map((e) => e!)
.toList();
【问题讨论】:
标签: dart dart-null-safety
像这样的东西使它更干净一点:
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]
}
【讨论】:
您可以像这样使用非常流行的collection package(这是 Dart 团队发布的官方核心包):
final list2 = list1.whereNotNull();
或者正如评论所指出的,如果你不希望它作为一个可迭代的:
final list2 = list1.whereNotNull().toList();
作为参考,其实现如下(如果您出于某种原因不想包含该包,而是自己在自己的文件中创建扩展名):
/// 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;
}
}
}
【讨论】:
Iterable<T>。因此,您的示例 var list2 = list1.whereNotNull(); 应该记住在将其保存到变量之前将其转换为列表。 :)