【问题标题】:Flutter getting data from API to build methodFlutter 从 API 获取数据以构建方法
【发布时间】: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

标签: api flutter dart


【解决方案1】:

我更改了您的代码,因此 Text 小部件是在 getData 完成处理 http 响应数据之后构建的。

const apiKey = 'xxxxxx';
const coinApiURL = 'https://rest.coinapi.io/v1/exchangerate';

class _CurrencyState extends State<CurrencyScreen> {

// fetch http data and return rate value 
Future<double> getData() async {
http.Response response = await http.get('$coinApiURL/BTC/USD?apikey=$apiKey');
String data = response.body;
double exchangeRate = jsonDecode(data)['rate'];
print(exchangeRate);
// return exchangeRate value
return exchangeRate;
}

@override
  Widget build(BuildContext context) {
  return FutureBuilder<double>(
    // assign getData() to futureBuilder
    future: getData(),
    builder: (BuildContext  context, AsyncSnapshot<double> snapshot) {
      // handle getData error
      if (snapshot.hasError) {
        return Text('Error');
      }
      // handle success fetched data
      if (snapshot.hasData) {
        return Text(snapshot.data.toString());
      }
      // return progress indicator while loading data
      return Center(child: CircularProgressIndicator());
    },
     );
  }

【讨论】:

    猜你喜欢
    • 2020-02-27
    • 2019-08-26
    • 2021-07-20
    • 2021-06-27
    • 1970-01-01
    • 2021-05-24
    • 2021-08-20
    • 2021-06-10
    • 2021-11-25
    相关资源
    最近更新 更多