'Future<dynamic>' 颤振错误的实例

时间:2020-12-29 19:25:47

标签: flutter dart

伙计们,我在从这个未来功能中获取价值时遇到了问题。

Future getData() async {
    http.Response response = await http.get(siteAddress + '?apikey=' + apiKey);
    if (response.statusCode == 200) {
      var data = jsonDecode(response.body);
      double price = data['rate'];
      String finalData = price.toStringAsFixed(0);
      return finalData;
    }else
      print(response.statusCode);
  }

Text(getData.toString());

当我在文本小部件中使用它时,我收到“未来”错误的实例。

1 个答案:

答案 0 :(得分:0)

getData() 返回一个 Future<String>,因此我们应该将其重写如下:

Future<String> getData() async {
    http.Response response = await http.get(siteAddress + '?apikey=' + apiKey);
    if (response.statusCode == 200) {
      var data = jsonDecode(response.body);
      double price = data['rate'];
      String finalData = price.toStringAsFixed(0);
      return finalData;
    }else
      print(response.statusCode);
}

并通过 TextWidget FutureBuilder 中使用它:

FutureBuilder(
  future: getData(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data);
    } else {
      return Text('Loading...');
    }
  },
),