Issue
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), ), ), )); } }
Solution
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();
}
)
)
);
}
Answered By - Roman Jaquez
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.