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),
];
});
}
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{}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With