我解决这个问题的方法如下。 table_calendar 版本:^3.0.3
LinkedHashMap<DateTime, List<AppEvent>> _groupedEvents;
DateTime _focusedDay = DateTime.now();
DateTime _selectedDay = DateTime.now();
@override
void didChangeDependencies() {
// context.read(pnProvider).init();
super.didChangeDependencies();
}
int getHashCode(DateTime key) {
return key.day * 1000000 + key.month * 10000 + key.year;
}
_groupEvents(List<AppEvent> events) {
_groupedEvents = LinkedHashMap(equals: isSameDay, hashCode: getHashCode);
events.forEach((event) {
DateTime date = DateTime.utc(
event.startDate.year, event.startDate.month, event.startDate.day, 12);
if (_groupedEvents[date] == null) _groupedEvents[date] = [];
_groupedEvents[date].add(event);
});
}
List<dynamic> _getEventsForDay(DateTime date) {
return _groupedEvents[date] ?? [];
}
final eventList = getEvents();
static List<AppEvent> getEvents() {
List<AppEvent> events = [];
AppEvent appEvent = AppEvent();
appEvent.id = "12";
appEvent.userId = "15";
appEvent.title = "Calendar";
appEvent.description = "this is the event1";
appEvent.startDate = DateTime.now();
events.add(appEvent);
appEvent = AppEvent();
appEvent.id = "13";
appEvent.userId = "16";
appEvent.title = "Calendar2";
appEvent.description = "this is the event2";
appEvent.startDate = DateTime(kNow.year, kNow.month, kNow.day + 1);
events.add(appEvent);
appEvent = AppEvent();
appEvent.id = "13";
appEvent.userId = "16";
appEvent.title = "Calendar2";
appEvent.description = "this is the event2";
appEvent.startDate = DateTime.now();
events.add(appEvent);
return events;
}
@override
void initState() {
_groupEvents(eventList);
super.initState();
}
@override
void dispose() {
super.dispose();
}
TableCalendar(
focusedDay: _focusedDay,
selectedDayPredicate: (day) => isSameDay(day, _selectedDay),
firstDay: kFirstDay,
lastDay: kLastDay,
eventLoader: _getEventsForDay,
onDaySelected: (selectedDay, focusedDay) {
setState(() {
_selectedDay = selectedDay;
_focusedDay = focusedDay;
});
print(_selectedDay);
print(_groupedEvents[_selectedDay]);
},
weekendDays: [6],
headerStyle: HeaderStyle(
decoration: BoxDecoration(
color: Colors.blueGrey,
),
headerMargin: const EdgeInsets.only(bottom: 8.0),
titleTextStyle: TextStyle(
color: Colors.white,
),
formatButtonDecoration: BoxDecoration(
border: Border.all(color: Colors.white),
borderRadius: BorderRadius.circular(10),
),
formatButtonTextStyle: TextStyle(color: Colors.white),
leftChevronIcon: Icon(
Icons.chevron_left,
color: Colors.white,
),
rightChevronIcon: Icon(
Icons.chevron_right,
color: Colors.white,
),
),
calendarStyle: CalendarStyle(
// Use `CalendarStyle` to customize the UI
outsideDaysVisible: false,
),
calendarBuilders: CalendarBuilders(),
)