flutter - 如何转换列表列出?
问题描述
我有一个返回类型为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
解决方案
三种解决方案
- 这将使用 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);
});
推荐阅读
- html - Golang 在按钮按下时呈现新模板
- laravel - 异常的 Livewire 行为:对象变为空数组
- java - JavaMailSender 使用 Kubernetes PodName 发送邮件
- css - 如何在 React 中使用带有样式组件的背景图像中的道具
- sql - 用给定字符串中的前一个字母替换
- python - LSTM 层之后的自定义注意力层在 Keras 中给出 ValueError
- r - file.exists() 结果是假的-但文件在那里
- javascript - 如何将一组句子拆分成json格式?
- swift - 使用 Alamofire.download() 请求时如何从响应正文中获取错误消息
- visual-studio-code - 尽管 c_cpp_properties 文件中的目录找不到头文件