本节目标

  • 调用异步 等待、递归
  • 异步返回值

环境

  • Dart 2.1.0

调用异步 回调

1
2
3
4
5
6
7
8
import 'package:dio/dio.dart';

void main() {
Dio dio = new Dio();
dio.get("https://www.baidu.com").then((response) {
print(response.data);
});
}

then 的方式异步回调

调用异步 等待

1
2
3
4
5
6
7
import 'package:dio/dio.dart';

void main() async {
Dio dio = new Dio();
Response<String> response = await dio.get("https://www.baidu.com");
print(response.data);
}

async 写在函数定义
await 写在异步请求头

异步返回值

1
2
3
4
5
6
7
8
9
10
11
12
import 'package:dio/dio.dart';

void main() async {
var content = await getUrl('https://www.baidu.com');
print(content);
}

Future<String> getUrl(String url) async {
Dio dio = new Dio();
Response<String> response = await dio.get(url);
return response.data;
}

定义 Future<T> 返回对象

代码

参考


© 猫哥

https://ducafecat.tech