Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for async in initState

Tags:

flutter

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 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.

How can I do that?

@override
  void initState() {
    super.initState();
    sendHealthData();
    _widgetOptions = <Widget>[
      HomeSubScreen(healthData),
    ];

  }

Update: If I added a then() I get the following error:

NoSuchMethodError: The method 'elementAt' was called on null.

Code Updated:

@override
      void initState() {
        super.initState();
        sendHealthData().then((response){
             _widgetOptions = <Widget>[
                 HomeSubScreen(healthData),
              ];
        });


      }
like image 258
Faabass Avatar asked Nov 25 '19 13:11

Faabass


1 Answers

You cannot await for async function in the initState, but a little trick is to use the Then keyword to execute code after that future complete.

eg:

@override


void initState() {
    super.initState();
    sendHealthData().then((response){

      _widgetOptions = <Widget>[
        HomeSubScreen(response),
      ];

    });


  }

and the function must be like:

Future sendHealthData() async{}
like image 125
Cristian Bregant Avatar answered Oct 06 '22 16:10

Cristian Bregant