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

Flutter中如何在Table Calendar中自定义日期单元格组件?

自定义Table Calendar日期单元格展示支出数据

Table Calendar组件完全支持自定义日期单元格,你可以通过calendarBuilders属性替换默认日期显示,实现将日期数字替换为当日支出的需求。

实现方案

  1. 通过calendarBuilders参数重写defaultBuilder方法,自定义每个日期单元格的UI
  2. 根据当前日期的天数,从myMap中匹配对应支出金额,无数据时可显示默认内容或空

完整代码示例

Map<int, double> myMap = {
  1: 200.00,
  2: 400.00,
  3: 500.00,
  // 补充更多日期-支出数据
};

@override
Widget build(BuildContext context) {
  return TableCalendar(
    headerVisible: false,
    focusedDay: DateTime(year, month, 1),
    firstDay: DateTime(year, month, 1),
    lastDay: DateTime(year, month + 1, 0), // 获取当前月份最后一天
    // 核心:自定义日期单元格逻辑
    calendarBuilders: CalendarBuilders(
      defaultBuilder: (context, day, focusedDay) {
        double? expense = myMap[day.day];
        return Center(
          child: Text(
            expense != null ? '$expense' : '',
            style: TextStyle(fontSize: 14),
          ),
        );
      },
      // 可选:自定义选中日期的样式
      selectedBuilder: (context, day, focusedDay) {
        double? expense = myMap[day.day];
        return Container(
          decoration: BoxDecoration(
            color: Colors.blue,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Center(
            child: Text(
              expense != null ? '$expense' : '${day.day}',
              style: TextStyle(color: Colors.white),
            ),
          ),
        );
      },
    ),
  );
}

关键说明

  • defaultBuilder控制默认状态下的日期单元格样式,可直接用支出金额替换原日期数字
  • selectedBuilder可单独定义选中日期的样式,提升交互体验
  • 可根据需求调整单元格内的布局、字体、颜色等,匹配你的UI设计

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 14:22:32