Katana
Katana

Reputation: 421

Widget not updating in flutter

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?

Upvotes: 1

Views: 262

Answers (2)

magicleon94
magicleon94

Reputation: 5172

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.

Upvotes: 2

pauloamaral93
pauloamaral93

Reputation: 29

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.

Upvotes: 0

Related Questions