1

I have a method called getData for a stateful widget

void getData() async{
var bitCoinPrice1 = (await coinData.getPriceData('BTC$selectedCurrency')).toStringAsFixed(2);
bitCoinPrice = bitCoinPrice1;
} 

I am calling this method inside a drop down change event

  onChanged: (String newValue) {
    setState(
      () {
        selectedCurrency = newValue;
        print("Selected currency changed to $selectedCurrency");
        getData();
      },
    );
  }

Unless I enclose the contents in getData in another setState(), the value of bitcoinPrice doesn't reflect in the widget. My questions is : If call to getData() is already inside setState(), why does it require to have another setState() call inside getData() to update the widget?

1
  • 1
    you are using await in getData method, so it takes time to complete process because of that you require setState over there. Commented Nov 6, 2019 at 15:10

2 Answers 2

2

getData is async, so the execution of the body for setState terminates immediately, updating the state before the async result is delivered. Since setState doesn't allow an async body you have to do things differently.

Given the code you've provided, you could do something like this:

onChanged: (String newValue) {
    selectedCurrency = newValue;
    print("Selected currency changed to $selectedCurrency");
    getData();
}

and update the getData code like this:

void getData() async{
  var bitCoinPrice1 = (await coinData.getPriceData('BTC$selectedCurrency')).toStringAsFixed(2);
  setState({
    bitCoinPrice = bitCoinPrice1;
  });
} 

This way the setState will be called after the await-ed operation is done.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, you need another setState() inside getData() function, because can take more time to conclude getPriceData function (async method). After

bitCoinPrice = bitCoinPrice1;

You need to call setState to refresh widgets.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.