CalendarGridData constructor
Creates calendar grid data for the specified month and year.
Automatically calculates and includes dates from previous and next months to fill complete weeks in the grid.
Implementation
factory CalendarGridData({required int month, required int year}) {
DateTime firstDayOfMonth = DateTime(year, month, 1);
int daysInMonth = DateTime(year, month == 12 ? 1 : month + 1, 0).day;
int prevMonthDays = firstDayOfMonth.weekday;
DateTime prevMonthLastDay =
firstDayOfMonth.subtract(Duration(days: prevMonthDays));
List<CalendarGridItem> items = [];
int itemCount = 0;
if (prevMonthDays < 7) {
for (int i = 0; i < prevMonthDays; i++) {
int currentItemIndex = itemCount++;
items.add(CalendarGridItem(
prevMonthLastDay.add(Duration(days: i)),
currentItemIndex % 7,
true,
currentItemIndex ~/ 7,
));
}
}
for (int i = 0; i < daysInMonth; i++) {
int currentItemIndex = itemCount++;
DateTime currentDay = DateTime(year, month, i + 1);
items.add(CalendarGridItem(
currentDay,
currentItemIndex % 7,
false,
currentItemIndex ~/ 7,
));
}
int remainingDays = (7 - (items.length % 7)) % 7;
DateTime nextMonthFirstDay = DateTime(year, month + 1, 1);
if (remainingDays < 7) {
for (int i = 0; i < remainingDays; i++) {
int currentItemIndex = itemCount++;
items.add(CalendarGridItem(
nextMonthFirstDay.add(Duration(days: i)),
currentItemIndex % 7,
true,
currentItemIndex ~/ 7,
));
}
}
return CalendarGridData._(month, year, items);
}