我有一个异步函数,需要在有状态小部件的 initState 中调用,但我不能使用 await,因为 initState 不是异步的。
sendHealthData是async因为它从 Health Api 获取一些信息,然后我需要将该信息发送到 HomeSubScreen,这是另一个StatefulWidget. 但是在创建 HomeSubScreen 时,该sendHealthData方法没有获取所有信息,因此如果我尝试将参数中的某个值发送到HomeSubScreen,则该值将为空。
我怎样才能做到这一点?
@override
void initState() {
super.initState();
sendHealthData();
_widgetOptions = <Widget>[
HomeSubScreen(healthData),
];
}
Run Code Online (Sandbox Code Playgroud)
更新:如果我添加了 then() 我会收到以下错误:
NoSuchMethodError: The method 'elementAt' was called on null.
Run Code Online (Sandbox Code Playgroud)
代码更新:
@override
void initState() {
super.initState();
sendHealthData().then((response){
_widgetOptions = <Widget>[
HomeSubScreen(healthData),
];
});
}
Run Code Online (Sandbox Code Playgroud)
我给你一个大概的想法。
@override
void initState() {
super.initState();
function().then((int value) {
// future is completed you can perform your task
});
function2(); // or you can simply call the method if you don't want anything to do after future completes
}
Future<int> function() async {
// do something here
}
Future<int> function2() async {
// do something here
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用FutureBuilder
FutureBuilder<String>(
future: getYourDataFromApi(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('start widget');
case ConnectionState.active:
case ConnectionState.waiting:
return Text('Awaiting result from api...');
case ConnectionState.done:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
return Text('Result: ${snapshot.data}');
}
return null; // unreachable
},
)
Run Code Online (Sandbox Code Playgroud)
您不能在 initState 中等待异步函数,但有一个小技巧是使用 Then 关键字在 future 完成后执行代码。
例如:
@override
void initState() {
super.initState();
sendHealthData().then((response){
_widgetOptions = <Widget>[
HomeSubScreen(response),
];
});
}
Run Code Online (Sandbox Code Playgroud)
并且该函数必须类似于:
Future sendHealthData() async{}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7101 次 |
| 最近记录: |