You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中基于银行流水生成多维度报表的单方法实现优化问询

银行账本报表单方法优化实现

我正在开发一款银行账本App,目前刚学Flutter一周,手里有一份银行流水列表。需要在页面展示三类报表:

  • 年度报表:包含CashIn总额、CashOut总额
  • 月度报表:包含CashIn总额、CashOut总额
  • 日报表:包含CashIn总额、CashOut总额

已经写了一个getReport方法,支持按指定年、月、日获取报表,现在想优化这个单方法的实现,不用拆成三个独立方法。以下是优化后的完整代码:

class PassBookEntry {
  double amount;
  bool isDeposite;
  DateTime date;

  PassBookEntry({required this.amount, this.isDeposite = false, required this.date});
}

List<PassBookEntry> _allEntries = [
  PassBookEntry(amount: 10, date: DateTime(2023, 08, 11)),
  PassBookEntry(amount: 20, date: DateTime(2023, 08, 11)),
  PassBookEntry(amount: 30, date: DateTime(2023, 08, 12)),
  PassBookEntry(amount: 100, date: DateTime(2023, 08, 12), isDeposite: false),
];

Map<String, dynamic> getReport({required int year, int? month, int? day}) {
  // 过滤符合时间条件的流水记录
  final filteredEntries = _allEntries.where((entry) {
    if (entry.date.year != year) return false;
    if (month != null && entry.date.month != month) return false;
    if (day != null && entry.date.day != day) return false;
    return true;
  });

  // 统计CashIn和CashOut总额
  double cashInTotal = 0;
  double cashOutTotal = 0;
  for (final entry in filteredEntries) {
    if (entry.isDeposite) {
      cashInTotal += entry.amount;
    } else {
      cashOutTotal += entry.amount;
    }
  }

  // 也可以用fold实现更简洁的聚合:
  // final totals = filteredEntries.fold(
  //   {'cashIn': 0.0, 'cashOut': 0.0},
  //   (acc, entry) {
  //     entry.isDeposite ? acc['cashIn']! += entry.amount : acc['cashOut']! += entry.amount;
  //     return acc;
  //   },
  // );
  // double cashInTotal = totals['cashIn']!;
  // double cashOutTotal = totals['cashOut']!;

  return {
    'cashInTotal': cashInTotal,
    'cashOutTotal': cashOutTotal,
    'balance': cashInTotal - cashOutTotal,
  };
}

void main() {
  // 测试日报表:2023年8月12日
  var dailyReport = getReport(year: 2023, month: 8, day: 12);
  print('日报表余额:${dailyReport['balance']}'); // 输出-70

  // 测试月度报表:2023年8月
  var monthlyReport = getReport(year: 2023, month: 8);
  print('月度报表CashIn:${monthlyReport['cashInTotal']}'); // 输出60
  print('月度报表CashOut:${monthlyReport['cashOutTotal']}'); // 输出100

  // 测试年度报表:2023年
  var yearlyReport = getReport(year: 2023);
  print('年度报表余额:${yearlyReport['balance']}'); // 输出-40
}

实现说明

  1. 时间过滤逻辑:通过where方法逐步筛选,先匹配年份,再根据可选参数month和day缩小范围,逻辑清晰且灵活,同时支持三类报表的查询需求。
  2. 总额统计:提供两种统计方式——基础for循环直观易懂,fold方法更简洁聚合,可根据习惯选择。
  3. 参数兼容:利用可选参数特性,调用时只需传入对应层级参数即可(年度传year,月度传year+month,日报传year+month+day),无需拆分方法。

内容的提问来源于stack exchange,提问作者user22362195

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 10:25:24