匿名函数

1
2
3
4
5
6
7
8
9
10
test(Function calback) {
calback("hello");
}

main() {
test((param) {
// Print hello
print(param);
});
}

函数作为变量

1
2
3
4
var say = (str) {
print(str);
};
say("Hello, World!");

异步

  • Future 表示一个异步操作的最终完成(或失败)及其结果值的表示

  Future.delayed: 创建一个延时任务
  Future.then:接受异步结果

1
2
3
4
5
Futrue.delayed(new Duration(seconds: 2), () {
return "Hello, World!";
}).then(data) {
print(data);
});

  Future.wait 只有数组中 所有Future 都执行成功后,才会触发 then 的成功回调,只要有一个
  Future 执行失败,就会触发错误回调

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Future.wait([
// 2秒后返回结果
Future.delayed(new Duration(seconds: 2), () {
return "Hello, ";
}),
// 4秒后返回结果
Future.delayed(new Duration(seconds: 4), () {
return "World!";
})
]).then((results) {
print(results[0] + results[1]);
}).catchError((e) {
print(e);
});
  • Dart提供了类似ES7中的 async, await 等异步操作
  • asyncawait 往往是成对出现的,如果一个方法中有耗时的操作,你需要将这个方法设置成 async,并给其中的耗时操作加上 await关键字,如果这个方法有返回值,你需要将返回值塞到 Future 中并返回
1
2
3
4
5
6
7
8
9
10
11
12
13
import 'dart.async';
import 'package:http/http.dart' as http;

Future<String> getNetData() async {
http.Response res = await.get("http://www.baidu.com");
return res.body;
}

main() {
getNetData().then((str) {
print(str);
});
}