Home > front end >  Flutter ensure I have a value in Async/Await and init functions
Flutter ensure I have a value in Async/Await and init functions

Time:01-31

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();
  }

  getVids() 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!

CodePudding user response:

You can change your getVids to this:

Future<List> getVids() async {
  final String response = await rootBundle.loadString('assets/values.json');
  final vals = await json.decode(response)['values'];
  return vals;
}

then create another middle function like this:

callasyncs() async {
   var result = await getValues();
   configValue(result);
}

and call it inside initState like this:

@override
void initState() {
  super.initState();
  callasyncs();
}

also change your configValue to this:

void configValue(List values) {
  ...
}

CodePudding user response:

you need to use await before the method to complete the future. also can be use .then.

Future<void> getVids() async { //I prefer retuning value
  final String response = await rootBundle.loadString('assets/values.json');
  final vals = await json.decode(response)['values'];
  setState(() {
    values = vals;
  });
}

void configValue() async {
  await getVids();
   
}
  • Related