如何在initState中等待异步

编程入门 行业动态 更新时间:2024-10-25 00:27:01
本文介绍了如何在initState中等待异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个需要在有状态窗口小部件的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中等待异步

本文发布于:2023-11-12 18:55:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582268.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   initState

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!