Flutter-Daily-Interview
Flutter-Daily-Interview copied to clipboard
第005期 await for的使用方式
代码如下
String data;
getData() async {
data = await http.get(Uri.encodeFull(url), headers: {"Accept": "application/json"}); //延迟执行后赋值给data
}
- await关键字必须在async函数内部使用
- 调用async函数必须使用await关键字
- 返回默认是一个future对象
//定义了返回结果值为String类型
Future<String> getDatas(String category) async {
var request = await _httpClient.getUrl(Uri.parse(url));
var response = await request.close();
return await response.transform(utf8.decoder).join();
}
run() async{
int data = await getDatas('keji'); //因为类型不匹配,IDE会报错
}
Furture的作用是为了链式调用
//案例3
funA(){
...set an important variable... //设置变量
}
funB(){
...use the important variable... //使用变量
}
main(){
new Future.then(funA()).then(funB()); // 明确表现出了后者依赖前者设置的变量值
new Future.then(funA()).then((_) {new Future(funB())}); //还可以这样用
//链式调用,捕获异常
new Future.then(funA(),onError: (e) { handleError(e); }).then(funB(),onError: (e) { handleError(e); })
}
await for 常用于Stream