1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 泛型常用于需要类型安全的情况。
// 适当的指定泛型可以更好地帮助代码生成。
// 使用泛型可以减少代码重复。

var names = <String>[];
names.addAll(['11', '22']);
// names.add(2); The argument type 'int' can't be assigned to the parameter type 'String'

// 减少代码重复
abstract class ObjectCache {
Object getByKey(String key);
void setByKey(String key, Object value);
}

abstract class StringCache {
String getByKey(String, key);
void setByKey(String key, String value);
}

abstract class Cache<T> {
T getByKey(String key);
void setByKey(String key, T value);
}
  • 使用集合字面量
1
2
3
4
5
6
// List、Set 以及 Map 字面量也可以是参数化的。定义参数化的 List 只需在中括号前添加 <type>;定义参数化的 Map 只需要在大括号前添加 <keyType, valueType>:

var names = <String>['Seth', 'Kathy'];
var uniqueNames = <String>{'Seth', 'Kathy'};
var pages = <String, String>{'index': '111'};

  • 使用类型参数化的构造函数
1
2
3
4
// 在调用构造方法时也可以使用泛型,只需在类名后用尖括号(<...>)将一个或多个类型包裹即可:

var names = <String>['Seth', 'Kathy'];
var nameSet = Set<String>.from(names);
  • 泛型集合以及它们所包含的类型
1
2
3
4
5
6
7
8
// Dart的泛型类型是 固化的,这意味着即便在运行时也会保持类型信息:

var names = <String>[];
names.add("value");
// print(names is List<String>); true
// print(names is List); true
// print(names is List<int>); true

  • 使用泛型方法
1
2
3
4
T first<T>(List<T> ts) {
T tem = ts[0];
return tem;
}