In your code in build
and initState
methods you retrieving the data from WEB but is not correct. If you need get the data each time when screen opening, you can use FutureBuilder widget (with it you can add a loader to providing information about current data retrieving state) and not call getNetData
from initState
. For update the data from a button (if you are choose FutureBuilder
), just call setState
(which calls build
method again and reload value).
Something like this:
class _MainPageState extends State<MainPage> {
String selectedValue = "USD";
Future<String> getRate() async {
HTTP.Response response = await HTTP.get('https://rest.coinapi.io/v1/exchangerate/BTC/$selectedValue?apikey=myKey');
if (response.statusCode == 200) {
return jsonDecode(response.body)['rate'];
} else {
// TODO: handle error code correctly
return '';
}
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: getRate(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
// The data is loading, show progress
return CircularProgressIndicator();
}
final rate = snapshot.data;
return Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Padding(
padding: EdgeInsets.all(20.0),
child: Container(
child: Card(
color: Colors.lightBlue,
child: ListTile(
title: Text(
'1 BTC = $rate USD DOLLAR',
textAlign: TextAlign.center,
),
),
),
),
),
),
],
),
Row(
children: <Widget>[
Expanded(
child: Container(
height: 150.0,
color: Colors.lightBlue,
child: Center(
child: DropdownButton(
value: selectedValue,
items: getDropDown(),
onChanged: (value) => setState(() {}),
),
),
),
),
],
),
],
);
},
);
}
List<DropdownMenuItem> getDropDown() {
List<DropdownMenuItem<String>> menuItems = [];
for (String items in list) {
var item = DropdownMenuItem(
child: Text(items),
value: items,
);
menuItems.add(item);
}
return menuItems;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…