How can I make sure I have a state variable available after an async function call? My belief is because getValues()
is async, it should "wait" until moving on to the next line. Thus, getValues()
shouldn’t exit and configValue()
shouldn’t be invoked until after my call to setState
has finished. However the behavior I’m seeing it that values
is an empty array in my Widget.
late List values = [];
@override
void initState() {
super.initState();
getValues();
configValue();
}
getValues() async {
final String response = await rootBundle.loadString('assets/values.json');
final vals = await json.decode(response)['values'];
setState(() {
values = vals;
});
}
void configValue() {
// How to make sure I have values[0] here?
}
Thanks in advance!
3
Answers
You can change your
getValues
to this:then create another middle function like this:
and call it inside
initState
like this:also change your
configValue
to this:here your both
configValue
andgetValues
are separated from each other and also yourconfigValue
will wait for thegetValues
result.you need to use
await
before the method to complete the future. also can be use.then
.Try the following code: