Flutter:如何将API交易数据按月份去重并汇总对应金额
Flutter 按月份汇总交易金额实现方案
需求说明
原始API返回的交易数据:
[ {"type": "expense", "amount": 250, "paymentDate": "22-02-2022"}, {"type": "income", "amount": 350, "paymentDate": "22-02-2022"}, {"type": "expense", "amount": 150, "paymentDate": "22-02-2022"}, {"type": "expense", "amount": 450, "paymentDate": "22-03-2022"}, {"type": "income", "amount": 650, "paymentDate": "22-03-2022"}, {"type": "expense", "amount": 650, "paymentDate": "22-05-2022"}, {"type": "income", "amount": 650, "paymentDate": "22-05-2022"}, {"type": "income", "amount": 650, "paymentDate": "22-05-2022"} ]
需要将同一月份的所有交易金额汇总,生成如下格式的列表:
[ {"x": 2, "y": 750}, {"x": 3, "y": 1100}, {"x": 5, "y": 1950} ]
实现步骤
1. 添加依赖
确保pubspec.yaml中引入intl包(用于日期解析):
dependencies: flutter: sdk: flutter intl: ^0.18.1
执行flutter pub get完成依赖安装。
2. 定义数据模型
创建交易数据模型类,简化数据处理流程:
class Transaction { final String type; final int amount; final String paymentDate; Transaction({ required this.type, required this.amount, required this.paymentDate, }); // 从JSON转换为模型实例 factory Transaction.fromJson(Map<String, dynamic> json) { return Transaction( type: json['type'], amount: json['amount'], paymentDate: json['paymentDate'], ); } }
3. 实现汇总逻辑
核心逻辑是按月份分组累加金额,代码如下:
import 'package:intl/intl.dart'; List<Map<String, int>> aggregateTransactionsByMonth(List<Transaction> transactions) { // 用Map存储月份对应的总金额,key为月份int,value为总金额 final Map<int, int> monthlyTotal = {}; for (final transaction in transactions) { // 解析日期,提取月份 final dateFormat = DateFormat('dd-MM-yyyy'); final date = dateFormat.parse(transaction.paymentDate); final month = date.month; // 累加金额到对应月份 if (monthlyTotal.containsKey(month)) { monthlyTotal[month] = monthlyTotal[month]! + transaction.amount; } else { monthlyTotal[month] = transaction.amount; } } // 将Map转换为目标格式的列表 return monthlyTotal.entries.map((entry) { return {"x": entry.key, "y": entry.value}; }).toList(); }
4. 完整使用示例
void main() { // 模拟API返回的原始数据 final rawTransactions = [ {"type": "expense", "amount": 250, "paymentDate": "22-02-2022"}, {"type": "income", "amount": 350, "paymentDate": "22-02-2022"}, {"type": "expense", "amount": 150, "paymentDate": "22-02-2022"}, {"type": "expense", "amount": 450, "paymentDate": "22-03-2022"}, {"type": "income", "amount": 650, "paymentDate": "22-03-2022"}, {"type": "expense", "amount": 650, "paymentDate": "22-05-2022"}, {"type": "income", "amount": 650, "paymentDate": "22-05-2022"}, {"type": "income", "amount": 650, "paymentDate": "22-05-2022"} ]; // 转换为模型列表 final transactions = rawTransactions.map((json) => Transaction.fromJson(json)).toList(); // 执行汇总 final result = aggregateTransactionsByMonth(transactions); // 打印结果 print(result); // 输出: [{"x":2, "y":750}, {"x":3, "y":1100}, {"x":5, "y":1950}] }
关键说明
- 日期解析:使用
intl包的DateFormat匹配原始日期的dd-MM-yyyy格式,确保准确提取月份。 - 分组累加:通过
Map作为中间容器,快速定位对应月份并累加金额,处理效率较高。 - 格式转换:最后将
Map键值对转换为目标要求的列表结构,直接满足输出需求。
内容的提问来源于stack exchange,提问作者user3352042
相关产品推荐
相关产品推荐

