【发布时间】:2020-12-30 16:48:29
【问题描述】:
在开始学习 Flutter 之前,我正在努力完成我认为很简单的事情。
const apiKey = 'xxxxxx';
const coinApiURL = 'https://rest.coinapi.io/v1/exchangerate';
class _CurrencyState extends State<CurrencyScreen> {
void getData() async {
http.Response response = await http.get('$coinApiURL/BTC/USD?apikey=$apiKey');
String data = response.body;
double exchangeRate = jsonDecode(data)['rate'];
print(exchangeRate);
}
@override
Widget build(BuildContext context) {
getData(); // prints out the value
print(exchangeRate); // error "Undefined name 'exchangeRate'"
(...)
child: Text($exchangeRate) // value has to be inserted here
}
所以虽然我可以使用函数 getData 来打印它包含的数据,但我无法打印出“exchangeRate”值。因此我也无法将值插入到 Text 小部件中。
谁能用简单的话解释一下它是如何工作的,以及如何获取“exchangeRate”变量的值并在代码中使用它?
【问题讨论】:
-
这并没有真正解决我的问题,但我更新了我的问题,以便更容易理解我想要完成的工作
-
你不能那样做,你有一个来自
getData()方法的Future,所以你必须使用我发布的链接中的FutureBuilder