首页 > 解决方案 > 如何转换列表列出?

问题描述

我有一个返回类型为List<T?>?. 我知道我可以使用!运算符将​​此返回类型转换为List<T?>,但我如何将其转换为List<T>

我试过的代码:

// testFunction returns List<T?>?
var test = testFunction() as List<T>? ?? [];

结果:

The following _CastError was thrown building ...:
type 'List<T?>' is not a subtype of type 'List<T>?' in type cast

标签: flutterdart

解决方案


三种解决方案

  • 这将使用 b 中的默认值添加和替换 a 中的空值
    List<T?>? a = [];
    List<T>? b = a.map((e) => e ?? defaultValue).toList();

  • 这些不考虑空值
    List<T?>? a = [];
    List<T> b2 = a.filter((v) => v != null).toList();
    List<T?>? a = [];

    List<int>? b2 = [];
    a.forEach((e) {
      if (e != null) b2.add(e);
    });


推荐阅读