Flutter:尝试使用 jsonDecode - 错误:字符串不是索引错误类型 int 的子类型

问题描述

我想在 Flutter 中使用 CoinMarketCap API。但是我想将地图中的数据添加到列表中,会发生一个错误,它说: 'string' 类型不是 'index' 的 'int' 类型的子类型。 这是我的代码,我使用了本教程 Migrating to the new CoinMarketCap API with Flutter

 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])