要说,List在我的开发使用中,确实是最为频繁的了,那么如何使用list,也就成了一个问题,list提供的方法又有哪些
这些都是需要掌握理解的。
首先第一个,
对于固定长度的list,如何删除添加元素呢void main() {
// 声明一个固定长度的集合
List numList = List(5);
numList[0] = 1;
numList[1] = 2;
numList[2] = 3;
numList[3] = 4;
numList[4] = 5;
print('遍历元素:');
for (int value in numList) {
print(value);
}
print('----更新第一个元素为 10------');
numList[0] = 10;
print('遍历元素:');
numList.forEach((value) => print(value));
print('----将第一个元素置为NULL---');
numList[0] = null;
print('遍历元素:');
for (int i = 0; i < numList.length; i++) {
print('${numList[i]}');
}
}
动态长度的 List
我们直接看示例:对于动态长度的list,
声明一:
void main() {
// 动态长度的 集合
List list = List();
list.add(1);
list.add(2);
list.forEach((value) => print('$value'));
print('');
list.removeAt(0);
list.forEach((value) => print('$value'));
print('');
list.add(3);
list[0] = null;
list.forEach((value) => print('$value'));
}
声明二:
// 这样也是一个动态的集合
List letterList = ["A", "B", "C"];
letterList.add("D");
letterList.add("E");
letterList.forEach((letter) => print('$letter'));
循环遍历 List 中的数据
///代码清单 1-1
List testList = ["test1", "xioming", "张三", "xioming", "张三", "李四"];
///方式一 遍历获取List中的所有数据
testList.forEach((value) {
//value 就是List中对应的值
});
///方式二 遍历获取List中的所有的数据
for(int i=0;i print('$value'));
}
Map
Dart 中 Map 的特性和 Java 中的类似,都是以键值对的形式存放,Map 中的键是唯一的,但是值可以重复,Map 也是无序的。
下面看看 Dart 中 Map 的基本操作:
void main() {
Map letterMap = Map();
letterMap["a"] = "A";
letterMap["b"] = "B";
letterMap["c"] = "C";
// 检查是否存在某个 key
letterMap.containsKey("a");
// 更新某个 key 对应的 value,注意 value 为一个 Lambda 表达式
letterMap.update("a", (value) => "${value}AA");
// 获取 Map 的长度
letterMap.length;
// 删除 Map 中的某个元素
letterMap.remove("c");
// 清空 Map
letterMap.clear();
// 遍历所有的 key
for (String key in letterMap.keys) {
print('$key');
}
print('');
// 遍历所有的 value
for (String value in letterMap.values) {
print('$value');
}
print('');
// 遍历所有的 key-value
letterMap.forEach((key, value) => print('$key == $value'));
}
上述代码中使用的是构造方法的方式来创建 Map,我们还可以使用一下方式来创建:
Map studentScoreMap = {
"Jack": 90,
"Rost": 100,
"Mary": 30,
"LiLei": 56
};
studentScoreMap.forEach((name, source) => print('$name == $source'));
Callable
Callable 能让我们像调用方法一样调用某个类,不过我们在类中需要实现 call
方法:
void main() {
var personOne = Person();
var info = personOne("Jack", 18);
print('$info');
}
class Person {
// 实现 call 方法
String call(String name, int age) {
return "$name is $age years old";
}
}