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

Flutter如何在列表日期头部展示对应月度消费总金额

你可以通过提前统计各月消费总额、自定义粘性头部布局两步实现需求,具体实现逻辑和代码示例如下:

1. 预处理消费数据,按月份统计总金额

首先针对你的消费数据集,提前遍历计算每个月的总消费金额存储备用:

// 消费数据模型示例,可根据你实际业务调整
class ConsumeRecord {
  final DateTime tradeTime;
  final double amount;
  // 其他业务字段...
  ConsumeRecord({required this.tradeTime, required this.amount});
}

// 统计每个自然月的总消费
Map<String, double> getMonthlyTotal(List<ConsumeRecord> records) {
  Map<String, double> monthlyTotalMap = {};
  for (var record in records) {
    // 生成和分组规则匹配的月份key,格式为"年-月",例:2021-07
    String monthKey = "${record.tradeTime.year}-${record.tradeTime.month.toString().padLeft(2, '0')}";
    monthlyTotalMap.update(
      monthKey, 
      (currentValue) => currentValue + record.amount,
      ifAbsent: () => record.amount,
    );
  }
  return monthlyTotalMap;
}
2. 自定义粘性头部,右侧渲染总金额

使用sticky_grouped_list的groupSeparatorBuilder参数支持完全自定义头部布局,你只需将头部设置为左右布局,左侧放日期文本,右侧放对应月份的总金额即可:

// 提前调用统计方法拿到月度总额
final Map<String, double> monthlyTotal = getMonthlyTotal(yourTradeRecordList);

StickyGroupedListView<ConsumeRecord, String>(
  elements: yourTradeRecordList,
  // 分组规则和统计时的monthKey保持完全一致
  groupBy: (element) => "${element.tradeTime.year}-${element.tradeTime.month.toString().padLeft(2, '0')},
  // 自定义头部布局
  groupSeparatorBuilder: (String groupKey) {
    // 将monthKey格式化显示为"2021年7月"
    final dateSeg = groupKey.split('-');
    final showDate = "${dateSeg[0]}年${int.parse(dateSeg[1])}月";
    // 读取对应月份的总消费,默认值设为0
    final totalAmount = monthlyTotal[groupKey] ?? 0.0;

    return Container(
      height: 42,
      padding: const EdgeInsets.symmetric(horizontal: 15),
      color: const Color(0xFFF5F5F5),
      alignment: Alignment.centerLeft,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            showDate,
            style: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500),
          ),
          Text(
            "月总消费:¥${totalAmount.toStringAsFixed(0)},
            style: const TextStyle(
              fontSize: 13,
              color: Colors.redAccent,
            ),
          )
        ],
      ),
    );
  },
  itemBuilder: (context, ConsumeRecord element) {
    // 原有列表项的布局逻辑保持不变即可
    return YourTradeItemWidget(record: element);
  },
  // 其他原有配置(排序、滚动参数等保留即可
);
注意事项
  • 若你的列表支持分页加载,每次新增数据后需要重新调用getMonthlyTotal更新月度总额再刷新UI即可
  • 如果需要调整分组规则(比如按周、按年统计),只需要同步修改groupBy返回的key和统计时的key生成规则即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 13:15:02