skip to Main Content

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


  1. You can change your getValues to this:

    Future<List> getValues() 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) {
      // now you have updated values here.
    }
    

    here your both configValue and getValues are separated from each other and also your configValue will wait for the getValues result.

    Login or Signup to reply.
  2. 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();
       
    }
    
    Login or Signup to reply.
  3. Try the following code:

    List? values;
    
    @override
    void initState() {
      super.initState();
      getValues();
      configValue();
    }
    
    Future<void> getVids() async {
      final String response = await rootBundle.loadString('assets/values.json');
      final vals = await json.decode(response)['values'];
      setState(() {
        values = vals;
      });
    }
    
    void configValue() {
      if (values != null) {
        if (values!.isNotEmpty) {
          …
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search