如何转换 List<String?>到列表<字符串>在空安全 Dart 中? [英] How to convert a List<String?> to List<String> in null safe Dart?
问题描述
我有一个飞镖列表:
List<String?> vals;
我想删除任何空值并将其转换为 List
.我试过了:
I want to remove any null values and convert it to a List<String>
.
I've tried:
List<String> removeNulls(List<String?> list) {
return list.where((c) => c != null).toList() as List<String>;
}
在运行时我收到以下错误:
At run time I'm getting the following error:
List<String?>' is not a subtype of type 'List<String>?'
解决这个问题的正确方法是什么?
What is the correct way to resolve this?
推荐答案
理想情况下,您首先应从
List
开始.如果您正在构建您的列表,例如:Ideally you'd start with a
List<String>
in the first place. If you're building your list like:String? s = maybeNullString(); var list = <String?>[ 'foo', 'bar', someCondition ? 'baz' : null, s, ];
那么你可以使用 collection-
if
来避免插入null
元素:then you instead can use collection-
if
to avoid insertingnull
elements:String? s = maybeNullString(); var list = <String?>[ 'foo', 'bar', if (someCondition) 'baz', if (s != null) s, ];
一种从
Iterable
中过滤掉null
值的简单方法并得到一个Iterable<;T>
结果是使用.whereType
.例如:() An easy way to filter out
null
values from anIterable<T?>
and get anIterable<T>
result is to use.whereType<T>()
. For example:var list = <String?>['foo', 'bar', null, 'baz', null]; var withoutNulls = list.whereType<String>().toList();
另一种方法是使用 collection-
for
和 collection-if
:Another approach is to use collection-
for
with collection-if
:var list = <String?>['foo', 'bar', null, 'baz', null]; var withoutNulls = <String>[ for (var s in list) if (s != null) s ];
最后,如果你需要转换一个
List
的元素,其他的选择是使用List.from
:Finally, if you need to cast the elements of a
List
, other options are to useList.from
:var list = <String?>['foo', 'bar', null, 'baz', null]; var withoutNulls = List<String>.from(list.where((c) => c != null));
或者如果您不想创建新的
List
,Iterable.cast
:or if you don't want to create a new
List
,Iterable.cast
:var list = <String?>['foo', 'bar', null, 'baz', null]; var withoutNulls = list.where((c) => c != null).cast<String>();
这篇关于如何转换 List<String?>到列表<字符串>在空安全 Dart 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!