Flutter TableCalendar加载事件时所有日历日期均被标记问题求助
问题根源
你当前的eventLoader配置存在逻辑错误:不管组件传入的day参数是什么,你直接返回了全量的事件列表controller.eventsList。组件判断某一天是否需要展示事件标记的逻辑是:只要eventLoader返回的列表不为空,就会给当天加上标记,所以所有日期都被标记了。
解决步骤
方案一:调整数据存储为Map格式(查询效率更高)
第一步:声明按日期分组的事件存储结构
// 格式为<日期, 对应日期的事件列表> final Map<DateTime, List> eventMap = {};
第二步:处理API返回的日期数据并分组
final events = await _jobsServices.getEvents(); final eventsConvert = events .map((date) => (DateTime.parse(date.dataDoJob))) .toList(); // 遍历日期按天分组 for (var eventDay in eventsConvert) { // 清零时间部分,仅保留年月日避免匹配偏差 final normalizedDay = DateTime(eventDay.year, eventDay.month, eventDay.day); if (eventMap[normalizedDay] == null) { eventMap[normalizedDay] = []; } // 无其他事件信息可直接存入占位对象 eventMap[normalizedDay]!.add('占位事件'); }
第三步:修正eventLoader配置
TableCalendar( // 重点修改eventLoader逻辑 eventLoader: (day) { final normalizedDay = DateTime(day.year, day.month, day.day); return eventMap[normalizedDay] ?? []; }, // 其余原有配置保持不变 calendarBuilders: const CalendarBuilders(), focusedDay: controller.focusedDay.value, firstDay: DateTime(2019), lastDay: DateTime(2050), headerStyle: const HeaderStyle(formatButtonVisible: false), locale: 'pt_BR', daysOfWeekVisible: true, calendarFormat: controller.format.value, onFormatChanged: (CalendarFormat _format) => controller.calendarFormat(_format), onDaySelected: (DateTime userSelectedDay, DateTime focusedDay) => controller.selectedDay(userSelectedDay, focusedDay), calendarStyle: CalendarStyle( selectedTextStyle: const TextStyle(color: Colors.white), isTodayHighlighted: true, selectedDecoration: BoxDecoration( color: context.buttomThemeClicled, shape: BoxShape.circle)), selectedDayPredicate: (DateTime date) { return isSameDay(controller.focusedDay.value, date); }, );
方案二:不修改原有List结构,直接在eventLoader中过滤
如果你不想调整原有数据结构,可以直接用组件自带的isSameDay方法过滤匹配的日期:
eventLoader: (day) { return controller.eventsList.where((eventDay) => isSameDay(eventDay, day)).toList(); },
该方法会自动忽略时间部分的差异,无需手动处理日期归一化也能正确匹配。
内容的提问来源于stack exchange,提问作者flavio_vieira_stack
相关产品推荐
相关产品推荐

