Home > Enterprise >  Api Call in flutter, data returned as list in list
Api Call in flutter, data returned as list in list

Time:12-21

I am trying to build an app which gets crypto date via an API, coingeckoAPI.

I have managed to recieve a list of cryptos into the app, however, now i am trying to import price data from a certain time range. This is how I am trying to do it: I want to get a list of data which according to the api link i am calling contains a timestamp and a value (price). But when i try and print a variable which is equal to the return of the API i only get this: "[]". But I want it to return a list of lists of the data, as shown in the bottom of the message.

void getGraphData(DateTime range) async {
    int date = range.toUtc().millisecondsSinceEpoch;
    int maxDate = DateTime.now().toUtc().millisecondsSinceEpoch;

    var data = await get(
      Uri.parse(
          "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart/range?vs_currency=usd&from=$date&to=$maxDate"),
    );
    if (data.statusCode == 200) {
      List<dynamic> dataList = [];
      dataList = jsonDecode(data.body)["prices"];
      
      print(dataList);
    }
  }

The API data is formatted like this:

{
"prices": [
[
1612137600000,
33064.78676701507
],
[
1612224000000,
33405.99035714327
],
[
1612310400000,
35485.98593382442
],
[
1612396800000,
37494.71762460426
],
],
}

If you want to check it out see here: https://api.coingecko.com/api/v3/coins/bitcoin/market_chart/range?vs_currency=usd&from=1612129039&to=1640039904.

I do not know how to access the data in the inner list. So a list of these lists, as shown above

[
    1612137600000,
    33064.78676701507
    ],

CodePudding user response:

I added an example of how to access the inner list


  void getGraphData(DateTime range) async {
    int date = range.toUtc().millisecondsSinceEpoch;
    int maxDate = DateTime.now().toUtc().millisecondsSinceEpoch;

    var data = await get(
      Uri.parse(
          "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart/range?vs_currency=usd&from=$date&to=$maxDate"),
    );
    if (data.statusCode == 200) {
      List<dynamic> dataList = [];
      dataList = jsonDecode(data.body)["prices"];
      
      final firstItem = dataList.first;
      print('First: ${firstItem.first} - Last: ${firstItem.last}');
      
    }
  }

CodePudding user response:

Try using map() or forEach() on the non-null list and only if you are certain about the number of fields is constant in each array item (here 2 is the size) as below:

var list = dataList.map((e) => {"time" : e[0], "value" : e[1]}).toList(growable : true);

You have converted the array to map with keys time and value which you can use easily further.

  • Related