【问题标题】:Flutter: trying to use jsonDecode - Error: string is not a subtype of type int of index ErrorFlutter:尝试使用 jsonDecode - 错误:字符串不是索引错误的 int 类型的子类型
【发布时间】:2021-03-25 13:51:44
【问题描述】:

我想在 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);
});

提前谢谢你。

【问题讨论】:

标签: flutter cryptography cryptoapi jsondecoder


【解决方案1】:

我今天遇到了同样的问题,我用这段代码修复了它。该代码与您的代码略有不同,但应该做同样的事情。如果它不起作用,请告诉我。

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);
});

}

【讨论】:

    【解决方案2】:

    改变这一行

    cryptoDatas.add(responseJSON["data"][i.toString()])
    

    到:

    cryptoDatas.add(responseJSON["data"][i])
    

    【讨论】:

      猜你喜欢
      • 2020-10-03
      • 2020-08-07
      • 2021-05-10
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2021-11-16
      相关资源
      最近更新 更多