我想在flutter中使用CoinMarketCap API。但在我想将数据从地图添加到列表的地方,会出现一个错误,上面写着:类型"string"不是"index"的类型"int"的子类型。这是我的代码,我使用了这个教程迁移到带有Flutter 的新CoinMarketCap API
Future<void> getCryptoPrices() async{
List cryptoDatas = [];
print('Crypto Prices are Loading...');
String apiURL= "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
http.Response response = await http.get(apiURL, headers: {'X-CMC_PRO_API_KEY': 'api code'});
Map<String, dynamic> responseJSON = json.decode(response.body);
if (responseJSON["status"]["error_code"] == 0) {
for (int i = 1; i <= responseJSON["data"].length; i++) {
cryptoDatas.add(responseJSON["data"][i.toString()]); // THE ERROR WILL HAPPEND HERE
}
}
setState(() {
this.cryptoList = cryptoDatas;
print(cryptoList);
});
提前谢谢。
我今天遇到了同样的问题,我用这段代码解决了它。代码与您的代码有点不同,但应该做相同的事情。如果不起作用,请告诉我。
Future<String> getCryptoPrices() async {
// API URL
var response = await http.get(
Uri.parse("API URL"),
// Only Accepts data in the formate of json
headers: {
"Accept": "application/json",
});
// this gets the data from the json
var first = json.decode(response.body);
//this is optional if you want to filter through the data
var second = first['current'];
var third = second['temp'];
// this prints out the data from the json
setState(() {
print(third);
});
}
更改此行
cryptoDatas.add(responseJSON["data"][i.toString()])
至:
cryptoDatas.add(responseJSON["data"][i])