flutter - Flutter 中对未来和异步编程的误导性概念
问题描述
Future
我发现它与async
编程的概念有点混淆。
根据定义,Future
是异步函数将返回的类型Future
。
目的是我们希望程序在等待async
函数结果的同时继续运行。
我不明白的是,我经常/总是看到人们使用async
whichawait
停止继续执行程序,直到它从调用的异步函数中获得结果。
我们不是绕了一圈吗?起初,async
进入我们不想等待程序占用时间的情况。但是现在,我们使用async
withawait
等到结果出来
解决方案
并不总是需要await
与未来一起使用。await
如果您想对数据进行进一步处理,可以使用。例子:
Future<int> _getInt()async{
Future.delay(Duration(seconds:3)); //simulating network delay
return 7;
}
void _add() async{
int res = await _getInt() + 10; //need to await because we are going to use a future variable
_putInt(res); //not nesscary to await if you don't want to handle the response
/* Ex: var result = await _putInt(); // if you want to handel the response
if (result.statusCode==200){
// handle success
}else{
// handle error
}*/
}
Future _putInt(int number)async{
var res = await http.post('url',body:{'data':number});
return res;
}
推荐阅读
- c# - CSS没有被拉入页面?
- machine-learning - 即使训练和测试始终相同,测试精度也会波动
- templates - 如何使模板构造函数参数可扣除?
- vuejs2 - VueJs:无效的道具:预期的布尔值,未定义
- sql - 不和谐机器人 | 基于 SQLite 的积分系统
- java - 是否可以通过使用 JNI 来避免 jvm 安全性?
- angular - Angular 拦截器在导入模块中使用拦截器的顺序
- spring-boot - WebFluxConfigurer 上的 @EnableWebFlux 会按预期自动配置 ThymeleafViewResolver
- java - 如何在 MongoDb 中插入带虚线字段的嵌入式文档
- laravel - Laravel 7 如何获取父类别名(nested-eloquent)?