我有一个需要在有状态窗口小部件的initState中调用的异步函数,但是我不能使用await,因为initState不是异步的.
I have an async function that needs to be called in initState in an Stateful widget, but I cannot use await as initState is not async.
sendHealthData 是 async ,因为它从Health Api获取了一些信息,然后我需要将该信息发送到HomeSubScreen,后者是另一个 StatefulWidget .但是在创建HomeSubScreen时, sendHealthData 方法无法获取所有信息,因此,如果我尝试将参数值发送给 HomeSubScreen ,则值将为空.
sendHealthData is async as it get some information from the Health Api, and then I need to send that information to HomeSubScreen which is another StatefulWidget. But at the time the HomeSubScreen is created, the sendHealthData method didn't get all the information, so If I try to send some value in a param to the HomeSubScreen, the value will be null.
我该怎么做?
@override void initState() { super.initState(); sendHealthData(); _widgetOptions = <Widget>[ HomeSubScreen(healthData), ]; }更新:如果添加了then(),则会出现以下错误:
Update: If I added a then() I get the following error:
NoSuchMethodError: The method 'elementAt' was called on null.代码已更新:
@override void initState() { super.initState(); sendHealthData().then((response){ _widgetOptions = <Widget>[ HomeSubScreen(healthData), ]; }); } 推荐答案我给您关于它的一般概念.
I'm giving you general idea of it.
@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 }更多推荐
如何在initState中等待异步
发布评论