从 dart 语言列表中过滤 null 的最佳方法是什么

What is the best way to fillter null from a list in dart language

寻找相当于 python 过滤器的飞镖

a = ['', None,4]
[print(e) for e in filter(None,a)]

我的代码太丑了:

List a = [null,2,null];
List b=new List();
for(var e in a){if(e==null) b.add(e);}
for(var e in b){a.remove(e);}
print(a);

您可以像这样使用 List 的 removeWhere 方法:

List a = [null, 2, null];
a.removeWhere((value) => value == null);
print(a); // prints [2]
  a.where((x) => x != null).forEach(print);

在新的 dart 2.12 中,具有良好的 null 安全性,最好的方法是:

List<int?> a = [null,2,null];
final List<int> b = a.whereType<int>().toList();

在现代 Dart 中,您可以使用“collection if”和“collection for”,它们类似于 Python 的列表理解:

List a = [null, 2, null];
List b = [for (var i in a) if (i != null) i];
print(b); // prints [2]

来源:https://github.com/dart-lang/language/blob/master/accepted/2.3/control-flow-collections/feature-specification.md#composing

我用@Wesley Chang 的回答做了一个扩展函数。

  extension ConvertIterable<T> on Iterable<T?> {
    List<T> toNonNullList() {
      return this.whereType<T>().toList();
    }
  }

您可以像下面这样使用。

  List<int?> a = [null,2,null];
  final List<int> b = a.toNonNullList();

使用 null-safety 旧的 removeWhere 解决方案不再有效,如果结果列表的类型是非可为空。 removeWhere 后的转换也不起作用。

最好的选择是导入集合

import 'package:collection/collection.dart';

允许一个人做

List<int> a = [null, 2, null].whereNotNull().toList();
print(a);
>>> [2]