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