泛型
// 泛型
abstract class Cache<T> {
T getByKey(String key);
void setByKey(String key, T value);
}
// List Map 参数化字面量
var names = <String>['Seth', 'Kathy', 'Lars'];
var uniqueNames = <String>{'Seth', 'Kathy', 'Lars'};
var pages = <String, String>{
'index.html': 'Homepage',
'robots.txt': 'Hints for web robots',
'humans.txt': 'We are people, not machines'
};
// 使用参数化类型调用构造器
var nameSet = Set<String>.from(names);
var views = Map<int, View>();
// 运行期检测参数化类型
var names = List<String>();
names.addAll(['Seth', 'Kathy', 'Lars']);
print(names is List<String>); // true
// 对参数化类型施加限制
class Foo<T extends SomeBaseClass> {
// Implementation goes here...
String toString() => "Instance of 'Foo<$T>'";
}
class Extender extends SomeBaseClass {...}
var someBaseClassFoo = Foo<SomeBaseClass>();
var extenderFoo = Foo<Extender>();
var foo = Foo();
print(foo); // Instance of 'Foo<SomeBaseClass>'
var foo = Foo<Object>(); // error
// 泛型方法
T first<T>(List<T> ts) {
// Do some initial work or error checking, then...
T tmp = ts[0];
// Do some additional checking or processing...
return tmp;
}
程序库与可见性
// 引入内置的程序库
import 'dart:html';
// 引入其他程序库
import 'package:test/test.dart';
// 程序库前缀
import 'package:lib1/lib1.dart';
import 'package:lib2/lib2.dart' as lib2;
// Uses Element from lib1.
Element element1 = Element();
// Uses Element from lib2.
lib2.Element element2 = lib2.Element();
// 引入程序库的一部分
// Import only foo.
import 'package:lib1/lib1.dart' show foo;
// Import all names EXCEPT foo.
import 'package:lib2/lib2.dart' hide foo;
// 延迟引入程序库
import 'package:greetings/hello.dart' deferred as hello;
Future greet() async {
await hello.loadLibrary();
hello.printGreeting();
}
异步
// 调用异步函数
await lookUpVersion();
// 定义异步函数
Future checkVersion() async {
var version = await lookUpVersion();
// Do something with version
}
// 调用异步函数并处理异常
try {
version = await lookUpVersion();
} catch (e) {
// React to inability to look up the version
}
// 多次调用异步函数
var entrypoint = await findEntrypoint();
var exitCode = await runExecutable(entrypoint, args);
await flushThenExit(exitCode);
// 异步 main 函数
Future main() async {
checkVersion();
print('In main: version is ${await lookUpVersion()}');
}
// 定义异步函数
Future<String> lookUpVersion() async => '1.0.0';
// 异步循环
Future main() async {
// ...
await for (var request in requestServer) {
handleRequest(request);
}
// ...
}
生成器
// 同步生成器
Iterable<int> naturalsTo(int n) sync* {
int k = 0;
while (k < n) yield k++;
}
// 异步生成器
Stream<int> asynchronousNaturalsTo(int n) async* {
int k = 0;
while (k < n) yield k++;
}
// 递归生成器
Iterable<int> naturalsDownFrom(int n) sync* {
if (n > 0) {
yield n;
yield* naturalsDownFrom(n - 1);
}
}