Flutter TableCalendar添加事件报错:调用null的year属性
Flutter table_calendar 添加事件出现 NoSuchMethodError 解决办法
错误原因
错误提示The getter 'year' was called on null,核心问题是日期时区不匹配+事件匹配逻辑错误:
- 你用
DateTime.utc()创建事件日期,但table_calendar传入eventLoader的day是本地时间DateTime对象,两者即使年月日相同,也不是同一个实例,导致_events.keys.contains(day)始终返回false。 - 匹配失败后,后续逻辑意外触发了null对象的
year属性访问。
修复步骤
统一日期时区:将事件日期改为本地时间创建,避免UTC与本地时间的差异:
DateTime d = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 12);修改事件匹配逻辑:使用
table_calendar提供的isSameDay方法判断同一天,而不是直接比较DateTime对象:eventLoader: (day) { return _events.entries .where((entry) => isSameDay(entry.key, day)) .expand((entry) => entry.value) .toList(); },空安全规范:给
_selectedDate加上可空标记,符合Flutter空安全要求:DateTime? _selectedDate;
完整修正代码
Map<DateTime, List> _events = {}; DateTime _focusedDay = DateTime.now(); DateTime? _selectedDate; @override void initState() { super.initState(); _selectedDate = _focusedDay; // 使用本地时间创建事件日期 DateTime d = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 12); _events[d] = ["Event A"]; } @override Widget build(BuildContext context) { return Column( children: [ TableCalendar( focusedDay: _focusedDay, onDaySelected: (selectedDay, focusedDay) { if (!isSameDay(_selectedDate, selectedDay)) { setState(() { _selectedDate = selectedDay; _focusedDay = focusedDay; }); } }, eventLoader: (day) { return _events.entries .where((entry) => isSameDay(entry.key, day)) .expand((entry) => entry.value) .toList(); }, ), ], ); }
内容的提问来源于stack exchange,提问作者lirongr1996
相关产品推荐
相关产品推荐

