You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何去除列表空值?有没有类似Swift的compactMap方法

在Flutter(Dart)中实现类似Swift compactMap的列表空值过滤

Dart(Flutter的开发语言)提供了多种方式实现和Swift compactMap类似的功能,用来过滤列表中的null值并转换类型,以下是几种常用方法:

方法1:使用whereType(最简洁原生方法)

whereType<String>()会自动筛选出列表中类型为String的元素,直接排除null,是处理可空类型列表的首选方式:

List<String?> list1 = ['a', 'b', null, 'c'];
List<String> list2 = list1.whereType<String>().toList();

方法2:结合where和cast

如果需要更明确的过滤逻辑,可以先用where排除null,再通过cast转换类型:

List<String?> list1 = ['a', 'b', null, 'c'];
List<String> list2 = list1.where((element) => element != null).cast<String>().toList();

方法3:使用compactMap(需导入collection包)

Dart的collection包提供了和Swift同名的compactMap方法,行为完全一致,自动忽略返回null的结果:
首先确保项目依赖中包含collection(通常Flutter项目默认已集成),然后导入包并使用:

import 'package:collection/collection.dart';

List<String?> list1 = ['a', 'b', null, 'c'];
List<String> list2 = list1.compactMap((element) => element).toList();

内容的提问来源于stack exchange,提问作者Nguyễn Đức Thành

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:32:39