-1

how fetch data async in initstate and then create build method and pass data?

i want get data async from API in initstate and then create build method this is my code:

Future<void> getCurrency() async {
NetworkHelper networkHelper = await NetworkHelper(
    url: 'https://rest.coinapi.io/v1/exchangerate/BTC/USD?apikey=$kApiKey');
var currencyData = await networkHelper.getData();
currencyrate = currencyData['rate'];

}

late double rate;

@override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Center( child: Text( '1 BTC = $rate USD', style: TextStyle(fontSize: 20, color: Colors.black), ), ), )); } }

sianami
  • 979
  • 1
  • 3
  • 11

1 Answers1

1

Or you could use a FutureBuilder widget, which could just unwrap the data your calling inside that method; you could just return it as a Future of what your data is and the FutureBuilder can take care of it, as in:


Future<double> getCurrency() async {
   NetworkHelper networkHelper = await NetworkHelper(
    url: 'https://rest.coinapi.io/v1/exchangerate/BTC/USD?apikey=$kApiKey');
   var currencyData = await networkHelper.getData();
   double currencyrate = currencyData['rate'];
   return currencyrate;
}

Then inside your build method:

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: SafeArea(
      child: FutureBuilder(
        future: getCurrency(),
        builder: (context, snapshot) {
          
          if (snapshot.hasData) {
            var rate = snapshot.data as double;
            return Center(
              child: Text('1BTC = $rate USD', 
                 style: TextStyle(fontSize: 20, color: Colors.black)
            );
          }

          return CircularProgressIndicator();
        }
      )
    )
  );
}
Roman Jaquez
  • 2,499
  • 1
  • 14
  • 7