Home > database >  Flutter: How to fix setState() callback argument returned a Future error?
Flutter: How to fix setState() callback argument returned a Future error?

Time:09-29

My goal is to do a simple BitcoinApp. I am trying to get a method that is in the MyHomePageState class to call a method that I have in another class. When I compile and click on the button to give me the bitcoin info of USD I get the error of setState() callback argument returned to Future. Any advice or alternative that you can suggest me? I'm new to Flutter and adjusting.Here is my code:

///This piece of code is located in MyHomePageState Class
BitcoinCurrency _bitcoin = BitcoinCurrency();

  void _getUSDBitcoin(){
    setState(() async{
      _bitcoin.usdBitcoin();
    });
  }

///This is the class I have outside of MyHomePageState Class.
class BitcoinCurrency {

  ///Variables we want for the information
  String _disclaimer = "N/A";
  String _time = "N/A";
  String _currencyBitcoin = "N/A";

  ///Getters for our variables
  get disclaimer => _disclaimer;

  get time => _time;

  get currencyBitcoin => _currencyBitcoin;

  ///Methods()

  void usdBitcoin() async{
    var url = Uri.https('api.coindesk.com', '/v1/bpi/currentprice.json');
    var response = await http.get(url);

    var httpBody = response.body;

    var decoded = json.decode(httpBody);
    _disclaimer = decoded['disclaimer'];
    _time = decoded['time']['updated'];
    _currencyBitcoin = decoded['bpi']['USD']['rate'];
  }
}

CodePudding user response:

You can convert usdBitcoin void to Future<void>

 Future<void? usdBitcoin() async{
    var url = Uri.https('api.coindesk.com', '/v1/bpi/currentprice.json');
    var response = await http.get(url);

    var httpBody = response.body;

    var decoded = json.decode(httpBody);
    _disclaimer = decoded['disclaimer'];
    _time = decoded['time']['updated'];
    _currencyBitcoin = decoded['bpi']['USD']['rate'];
  }

And call setState like

 usdBitcoin().then((value) => setState(() {}));

CodePudding user response:

setState can't be an async function. usdBitcoin has to be a Future method, so you have to call it before the setState starts.

usdBitcoin method:

Future usdBitcoin() async{
    var url = Uri.https('api.coindesk.com', '/v1/bpi/currentprice.json');
    var response = await http.get(url);

    var httpBody = response.body;

    var decoded = json.decode(httpBody);
    _disclaimer = decoded['disclaimer'];
    _time = decoded['time']['updated'];
    _currencyBitcoin = decoded['bpi']['USD']['rate'];
}

In initState:

usdBitcoin().then(
    (value) => setState(
        () {
          
        },
    ),
)
  • Related