Flutter 由 Google 的工程师团队打造,用于创建高性能、跨平台的移动应用。Flutter 针对当下以及未来的移动设备进行优化,专注于 Android and iOS 低延迟的输入和高帧率。 Flutter 可以给开发者提供简单、高效的方式来构建和部署跨平台、高性能移动应用;给用户提供漂亮、快速的应用体验。(小编出版的书籍 大家可以阅读一下) Flutter 使用 Dart 语言来开发,Dart 集合中原生支持了四种类型:list、 map、queue、 set。 1 判断集合是否为空使用 .isEmpty 和.isNotEmpty//代码清单1 import 'package:flutter/cupertino.dart';
void main() { //定义集合 List<String> testList = ["张三", "李四"];
//判断集合为空 if (testList.isEmpty) { debugPrint("集合为空"); }
if (testList.isNotEmpty) { debugPrint("集合不为空"); } }

2 使用高阶函数来转换集合数据如果你有一个集合并且想要修改里面的内容转换为另外一个集合, 使用 .map()、 .where() 以及 Iterable 提供的其他函数会让代码更加简洁。 如下我定义一个普通的数据模型: //代码清单2 class TestPeople { int type; String name;
TestPeople(this.type, this.name); }
然后我再定义一个List集合来保存一组数据 //代码清单3 //定义集合 List<TestPeople> testList = [ TestPeople(1, "张三"), TestPeople(2, "李四"), TestPeople(1, "王五") ];
然后我期望把这个集合中类型(type)为1的数据筛选出来放到一个新的集合中: //代码清单4 //转换类型 var newList = testList .where( (people) => people.type == 1,//条件判断筛选 ) .map( (people) => people.name,//构建新的集合使用的数据 ) .toList();
可以运行测试用例来看一下: //代码清单5 ///输出一下 newList 的类型 /// List<String> debugPrint("${newList.runtimeType}");
for (String item in newList) { debugPrint("newList-> $item"); }

3 避免在集合 List 中使用 .forEach()forEach() 函数在 JavaScript 中被广泛使用, 这因为 JavaScript 中内置的 for-in 循环通常不能达到想要的效果,在 Flutter中不 List 不建议使用 forEach() ,如下代码(列表数据在本文章中2小节中创建的) 
正确的遍历方式应当是这样的: //代码清单6 for (var element in testList) { debugPrint("${element.name} "); }
forEach() 函数的正确使用方式如下: //代码清单7 Map<String, dynamic> map = { "测试1": "0098", "测试2": "0094", "测试3": "0095", }; map.forEach((key, value) { debugPrint("=> $key: $value"); });

4 使用 whereType() 按类型过滤集合list 里面包含了多种类型的对象, 我们需要获取这个List中整型类型的数据,通常我们可以使用 where() 来实现(不建议): //代码清单8 var objectList = [100, "测试", 200, "张三", 3000]; //筛选数据 var ints = objectList.where((e) => e is int).toList(); ///输出一下 ints 的类型 /// List<Object> debugPrint("${ints.runtimeType}");
编辑器会提示不建议这样写,因为返回的是一个 Object 类型的集合 
当然可以进行一下强制类型转换(代码冗长,并导致创建了两个包装器,获取元素对象要间接通过两层): //代码清单9 var objectList = [100, "测试", 200, "张三", 3000]; //筛选数据 //List<int> var ints2 = objectList.where((e) => e is int).cast<int>().toList(); //输出一下类型 debugPrint("${ints2.runtimeType}");
推荐写法:使用 whereType 函数来筛选一类型的数据 //代码清单10 var objectList = [100, "测试", 200, "张三", 3000]; //筛选数据 var ints3 = objectList.whereType<int>().toList(); //输出一下类型 List<int> debugPrint("${ints3.runtimeType}");
5 避免 使用 cast()在上述 “代码清单9中” 使用到 cast函数来强转 List的类型,实际中不建议这样操作。 推荐使用下面的方式来替代:
|