我已经创建了一个将TransactionList转换为MapList的方法,用于每日收入和每日支出的报告。
似输出
[ {“日期”:28-01-23,“总收入”:300.00,“总支出”:300.00,“余额”:0.00,
}、{ ...}、]
这是交易的数据
List<Transaction> transactions=[
Transaction(date: DateTime(2023,01,18), isExpense: true, amount: 100.00,),
Transaction(date: DateTime(2023,01,18), isExpense: true, amount: 200.00,),
Transaction(date: DateTime(2023,01,18), isExpense: false, amount: 300.00,),
Transaction(date: DateTime(2023,01,19), isExpense: false, amount: 200.00,),
Transaction(date: DateTime(2023,01,19), isExpense: false, amount: 100.00,),
];
我的方法工作得很好,但我认为它不是正确的编码,所以我想用一些先进的方式实现这个方法...
List<Map<String, dynamic>> dailyreport() {
//grouping data based on date field of transactions
var maplist = groupBy(transactions, (Transaction element) => element.date);
List<Map<String, dynamic>> reportlist = [];
//loop for each key
for (var x in maplist.keys) {
double sum_expenses = 0;
double sum_income = 0;
//getting transaction based on key value
List<Transaction> trans = maplist[x] as List<Transaction>;
for (int i = 0; i < trans.length; i++) {
if (trans[i].isExpense)
sum_expenses = sum_expenses + trans[i].amount;
else
sum_income = sum_income + trans[i].amount;
}
//adding map to reportlist
reportlist.add({
'date': x,
'expenses': sum_expenses,
'income': sum_income,
'balance': sum_income - sum_expenses,
});
}
return reportlist;
}
2条答案
按热度按时间yhqotfr81#
下面是另一种方法,同样使用
groupBy
,然后折叠结果列表值:eufgjt7s2#
下面是一个循环的try: