1

I am trying to calculate a sum based on variable from List < Map >. I have a list of Maps that contain the date(month/year) and the amount and I want to convert it into a list of maps where an amount is a sum of all 'amounts' from each date.

My current list that I want to conver looks like that

[{name: 8/2020, amount: 61606.50}, {name: 9/2020, amount: 18481.95}, {name: 9/2020, amount: 12937.36}, {name: 9/2020, amount: 9056.16}, {name: 9/2020, amount: 6339.31}, {name: 9/2020, amount: 4437.52}, {name: 9/2020, amount: 1725.70}, {name: 9/2020, amount: 1725.70}, {name: 8/2020, amount: 20535.50}, {name: 9/2020, amount: 68451.67}]

and I want to be look like that:

[{8/2020 : total}, {9/2020 : total}]

My code:

    List _list = [];

    var map = Map();

    var foodList = Provider.of<List<FoodItem>>(context);

    var list = foodList.map((e) {
      Map _map;

      List _list;
      _list = e.consumed.map((elo) {
        DateTime date;

        date = DateTime.fromMillisecondsSinceEpoch(elo['date']);

        var test = DateFormat('yM').format(date);

        double _price = e.price * elo['amount'];

        _map = {
          'name': test,
          'amount': _price.toStringAsFixed(2),
        };

        return _map;
      }).toList();
      return _list;
    }).toList();

    list.forEach((e) => _list.addAll(e));

    print(_list);

    _list.forEach((x) {
      var test;

      test = x['name'];

      return map[test] = !map.containsKey(test) ? (1) : (map[test] + 1);
    });

    if (map.isNotEmpty) print(map);
ByteMe
  • 1,575
  • 1
  • 12
  • 23
czaplexd
  • 13
  • 3

2 Answers2

2

You can use fold on the list to achieve this:

final result = list.fold<Map<String, double>>({}, (rMap, element) {
  final key = element['name'];
  if (rMap[key] == null)
    rMap[key] = 0;
  rMap[key] += element['amount'];
  return rMap;
});

print(result); // {8/2020: 82142, 9/2020: 123155.37}
Abion47
  • 22,211
  • 4
  • 65
  • 88
0

I think the best way for you to solve your issue would be using the collection package. For more details and examples please refer here. In short, this package contains a function groupBy which you are looking for (similar to SQL which simplifies working with collections A LOT).

kovalyovi
  • 1,006
  • 1
  • 9
  • 19