0

I want to use CoinMarketCap API in flutter. But where I want to add data from map to list, an error will occur which says: type 'string' is not a subtype of type 'int' of 'index'. here's my code, I used this tutorial 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);
});

Thank you in advance.

Negin
  • 1
  • This other question may help you out. Take a look. https://stackoverflow.com/questions/53416469/type-string-is-not-a-subtype-of-type-int-of-index – Eli Front Mar 25 '21 at 14:09

2 Answers2

0

I had this same problem today, and I fixed it with this code. The code is a little different from yours but should do the same thing. If it didn't work then let me know.

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

}

0

change this line

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

to:

cryptoDatas.add(responseJSON["data"][i])
Biruk Telelew
  • 1,161
  • 7
  • 13