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
相关产品推荐
相关产品推荐

