首页 > 解决方案 > Flutter 中对未来和异步编程的误导性概念

问题描述

Future我发现它与async编程的概念有点混淆。

根据定义,Future是异步函数将返回的类型Future

目的是我们希望程序在等待async函数结果的同时继续运行。

我不明白的是,我经常/总是看到人们使用asyncwhichawait停止继续执行程序,直到它从调用的异步函数中获得结果。

我们不是绕了一圈吗?起初,async进入我们不想等待程序占用时间的情况。但是现在,我们使用asyncwithawait等到结果出来

标签: flutterasynchronousfuture

解决方案


并不总是需要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;
}

推荐阅读