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

Flutter如何在TableCalendar中设置指定日期为节假日

自定义TableCalendar节假日规则(保留原有样式与交互)

要实现自定义指定日期、attendance数组日期+原有周末的节假日标记,核心是修改holidayPredicate的判断逻辑,其他样式和交互配置完全保留即可。

步骤1:定义所需数据与辅助函数

先准备自定义节假日列表、attendance数组,再写一个日期比较的辅助函数(避免DateTime时间部分干扰判断):

// 自定义指定节假日(示例:2月2日、2月15日、3月5日)
final List<DateTime> customHolidays = [
  DateTime(DateTime.now().year, 2, 2),
  DateTime(DateTime.now().year, 2, 15),
  DateTime(DateTime.now().year, 3, 5),
];

// 你的attendance数组(假设为DateTime类型)
final List<DateTime> attendanceDates = [
  // 示例数据,替换为你的实际数组
  DateTime(DateTime.now().year, 4, 10),
  DateTime(DateTime.now().year, 4, 12),
];

// 仅比较年月日的辅助函数
bool isSameDay(DateTime a, DateTime b) {
  return a.year == b.year && a.month == b.month && a.day == b.day;
}

步骤2:修改TableCalendar的holidayPredicate

替换原来仅判断周末的逻辑,将三个判断条件用逻辑或连接:

TableCalendar(
  firstDay: DateTime.utc(2020, 1, 1),
  lastDay: DateTime.utc(2030, 12, 31),
  focusedDay: DateTime.now(),
  // 核心修改:自定义节假日判断逻辑
  holidayPredicate: (date) {
    // 原有周末判断
    final isWeekend = date.weekday == DateTime.saturday || date.weekday == DateTime.sunday;
    // 判断是否在自定义节假日列表
    final isCustomHoliday = customHolidays.any((holiday) => isSameDay(holiday, date));
    // 判断是否在attendance数组中
    final isAttendanceDay = attendanceDates.any((attDay) => isSameDay(attDay, date));
    
    // 满足任一条件则标记为节假日
    return isWeekend || isCustomHoliday || isAttendanceDay;
  },
  // 保留原有样式配置(示例,替换为你的实际样式)
  calendarStyle: CalendarStyle(
    holidayTextStyle: TextStyle(color: Colors.redAccent),
    holidayDecoration: BoxDecoration(
      color: Colors.red.withOpacity(0.1),
      borderRadius: BorderRadius.circular(8),
    ),
    // 其他原有样式属性...
  ),
  // 保留原有交互配置(示例,替换为你的实际交互)
  onDaySelected: (selectedDay, focusedDay) {
    // 原有日期选中逻辑...
  },
  headerStyle: HeaderStyle(
    titleCentered: true,
    formatButtonVisible: false,
    // 其他原有头部样式...
  ),
  // 其他原有组件配置...
)

说明

  • 所有原有样式(如节假日文本颜色、背景)、交互(如日期选中事件、月份切换逻辑)都无需改动,仅替换holidayPredicate的判断逻辑即可
  • 如果需要支持跨年的自定义节假日,直接在customHolidays中添加对应年份的DateTime对象即可
  • isSameDay函数是关键,避免因为DateTime包含时分秒导致日期匹配失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 18:58:09