伙计们,我在从这个未来功能中获取价值时遇到了问题。
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());
当我在文本小部件中使用它时,我收到“未来”错误的实例。
答案 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);
}
并通过 Text
在 Widget
FutureBuilder
中使用它:
FutureBuilder(
future: getData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data);
} else {
return Text('Loading...');
}
},
),