【发布时间】:2020-10-17 04:33:35
【问题描述】:
查看此代码:
class SomeClass{
String someVariable;
SomeClass();
Future<String> getData () async {
Response response = await get('http://somewebsite.com/api/content');
Map map = jsonDecode(response.body); // do not worry about statuscode, trying to keep it minimal
someVariable = map['firstName'];
return 'This is the first name : $someVariable';
}
}
现在看看 main:
void main(){
String someFunction() async {
SomeClass instance = SomeClass(); // creating object
String firstNameDeclaration = await instance.getData().then((value) => value);
return firstNameDeclaration;
}
}
在使用 Future 时,例如在 firstNameDeclaration 的情况下,为什么我必须使用 .then() 方法来访问字符串对象,因为我正在等待函数完成?
在网上搜索时,有些人使用.then()其他人没有,我很困惑。
请帮助我更清楚地了解 Futures 和异步函数的整体工作原理。
【问题讨论】:
-
你应该看看dart's guidelines关于异步
标签: flutter asynchronous dart future