gpt4 book ai didi

flutter - 如何计算汇总表List

转载 作者:行者123 更新时间:2023-12-03 03:31:42 35 4
gpt4 key购买 nike

我正在尝试基于List 中的变量计算总和。我有一个包含日期(月/年)和金额的 map 列表,我想将其转换为 map 列表,其中金额是每个日期的所有“金额”的总和。
我想要转换的当前列表如下所示

[{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}]
我想看起来像这样:
[{8/2020:总计},{9/2020:总计}]
我的代码:
    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);

最佳答案

您可以在列表上使用fold实现此目的:

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}

关于flutter - 如何计算汇总表List <Map>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63568903/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com