微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。