Dart 中的集合主要包含三种类型,List,Set,Map。这个在Java语言中其实也有,只是没有Java中那么丰富。
Lists
这是一个使用频率非常高的集合。它有很多创建方式。
直接创建
dart
var grains = <String>[] //声明一个String类型的数组
var fruits = ['apples', 'oranges'];//也是声明一个String类型的数组
前者是直接确定类型。第二种方式是用类类型推断,间接的声明了数组元素的类型。它还可以直接通过一些构造方法来创建。如:
dart
var vegetables = List.filled(99, 'broccoli');
其实list的操作和Java很类似,基本上的方法都是支持的
dart
fruits.add('kiwis'); //添加单个元素
fruits.addAll(['grapes', 'bananas']); //添加多个元素
print(fruits[1]); // 输出下标为1的元素
var appleIndex = fruits.indexOf('apples');//查找元素的下标
fruits.clear();//清楚所有元素
Sets
Set是一个无序的集合。因为它是无序的,所以不能通过index下标来获取其中的元素。创建方式的话,也是有很多种。
dart
var ingredients = <String>{} // 注意,这里和list不一样,list是[],而Set是{}
var atomicNumbers = Set.from([79, 22, 54]);// 通过构造函数的方式创建
var ingredients = Set<String>(); // 通过默认构造函数创建
添加,删除,以及判断该元素是否已存在等部分数组通用操作都是支持的。
dart
ingredients.add('gold'); //添加单个元素
ingredients.addAll(['gold', 'titanium', 'xenon']); // 添加多个元素
ingredients.remove('gold'); // 删除某个元素
assert(ingredients.contains('titanium'));// 判断是否包含某个元素
print(intersection.length) // 获取数组元素个数
从set里取值相对有点麻烦,尤其是取某个特定的值。所以如果需要频繁的存、取操作的时候,就不是很适合使用Set。
dart
print(ingredients.toList()[0]) // 直接转化成list然后通过下标的方式获取它的某个值,这是一种方式。
但因为它是无序的,所以你存的顺序不确定,所以在你想取它的值的时候,你是不知道下标的。所以使用场景非常有限。
dart
var iterator = ingredients.iterator;
if (iterator.moveNext()) { // 先移动到第一个元素
var randomElement2 = iterator.current; // 然后获取当前元素
print(randomElement2);
}
所以我们大多数情况下去使用Set之后,取值都是通过迭代器的方式去遍历获取你想要的值。
Maps
Map也是一个使用非常频繁的集合了。它和list以及set有点不太一样,它是key-value的形式存值的。
创建Map的方式有多种
-
直接使用字面量创建
dart// // 定义一个存储学生信息的Map Map<String, dynamic> student = { 'name': 'Alice', 'age': 20, 'scores': {'math': 90, 'english': 85} // 嵌套Map }; print(student); // 输出: {name: Alice, age: 20, scores: {math: 90, english: 85}}
-
使用构造函数Map()
dartMap<String, int> scores = Map(); scores['math'] = 90; scores['english'] = 85; print(scores); // 输出: {math: 90, english: 85}
-
通过Map.from()复制现有Map
dartMap<String, int> original = {'a': 1, 'b': 2}; Map<String, int> copied = Map.from(original); copied['c'] = 3; print(copied); // 输出: {a: 1, b: 2, c: 3}
-
使用Map.of创建不可变Map
dartMap<String, int> immutableMap = Map.of({'x': 10, 'y': 20}); // 尝试修改会报错:immutableMap['z'] = 30; // 抛出异常
Map的常用方法和属性
-
添加/修改/访问元素
dartMap<String, int> scores = {'math': 90}; scores['english'] = 85; // 添加新键 scores['math'] = (scores['math'] ?? 0) + 5; //访问并且修改现有键的值 print(scores); // 输出: {math: 95, english: 85}
-
遍历Map
dartscores.forEach((key, value) { // 应为Map也是一个集合,集合都支持forEach这个方法来遍历其中的元素 print('$key: $value'); }); for (var entry in scores.entries) { // 也可以通过for循环,当然,还有while。do...while都可以。 print('${entry.key}: ${entry.value}'); } // 他们的输出都是: // math: 95 // english: 85
-
获取所有Key或者value
dartvar keys = scores.keys; // Iterable<String> var values = scores.values; // Iterable<int> print(keys); // 输出: (math, english) print(values); // 输出: (95, 85)
-
检查Key或者value是否存在
dartbool hasMath = scores.containsKey('math'); // true bool hasScore90 = scores.containsValue(90); // false(当前值是95) print(hasMath); // true
-
合并Map
dartMap<String, int> moreScores = {'science': 88}; scores.addAll(moreScores); print(scores); // 输出: {math: 95, english: 85, science: 88}
-
删除元素
dartscores.remove('english'); // 移除键"english" scores.clear(); // 清空所有元素
初期先了解一下这些常用的方法。方便后面学UI组件的时候能直接使用的的上,不用再去翻文档吧。