如何转换 List<String?>到列表<字符串>在空安全 Dart 中? [英] How to convert a List&lt;String?&gt; to List&lt;String&gt; in null safe Dart?

查看:23
本文介绍了如何转换 List<String?>到列表<字符串>在空安全 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 inserting null 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 an Iterable<T?> and get an Iterable<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 use List.from:

      var list = <String?>['foo', 'bar', null, 'baz', null];
      var withoutNulls = List<String>.from(list.where((c) => c != null));
      

      或者如果您不想创建新的ListIterable.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆