'Add Key for list of multiple object ~ dart

   final uri = Uri.parse(
        "https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h");
    final res = await http.get(uri);
    var data = (jsonDecode(res.body)).toList();



    var name = [
      "Datetime",
      "Open",
      "High",
      "Low",
      "Close",
      "Volume",
      "Close time",
      "Quote",
      "Number of trades",
      "taker buy",
      "taker buy quote",
      "ignore"
    ];

    var output = [
      for (var d in data) Map<String, String>.fromIterable(name,value: d)
    ];
    print(output);

Try:

var output = Map<String, dynamic>.fromIterables(name, data);

Error: Uncaught Error: Invalid argument(s): Iterables do not have same length.

Error 2: Unhandled Exception: type 'List' is not a subtype of type '((dynamic) => String)?'

Need output like below list:

   [ {Open time: 1650409200000, Open: 41395.38000000, High: 41539.90000000, Low: 41395.38000000, Close: 41493.18000000, Volume: 850.49595000, Close time: 1650412799999, Quote asset volume: 35269640.77746520, Number of trades: 22594, Taker buy base asset volume: 396.50601000, Taker buy quote asset volume: 16441271.67871090, Ignore: 0},
    {Open time: 1650412800000, Open: 41493.19000000, High: 41541.23000000, Low: 41250.26000000, Close: 41295.37000000, Volume: 1226.31947000, Close time: 1650416399999, Quote asset volume: 50763275.81698850, Number of trades: 35252, Taker buy base asset volume: 508.56187000, Taker buy quote asset volume: 21051672.90479120, Ignore: 0}]

i'am using for method for each object but it dose not return the list value.



Solution 1:[1]

You probably didn't notice that what you're doing is wrong

Map.fromIterables takes two lists (In your case, a String list and a dynamic list), and makes the first list's values the map's keys, and the second list's values the map's values.

But what you're saying to dart by

 Map<String, dynamic>.fromIterables(name, data);

Is actually: "Hey I have a String list, and a list with two lists, could you make it a Map please?"

So more simply, do the following:

//You make a list out of data[0] and data[1]
var output = [Map<String, dynamic>.fromIterables(name, data[0]), Map<String, dynamic>.fromIterables(name, data[1])];

Or, if data's length is variable you could use:

var output = [for(var d in data) Map<String, dynamic>.fromIterables(name, d)];
//For each element in data you parse the data

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1