table_calendar.dart
29.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
// Copyright 2019 Aleksander Woźniak
// SPDX-License-Identifier: Apache-2.0
import 'dart:math';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import 'package:simple_gesture_detector/simple_gesture_detector.dart';
import 'package:table_calendar/src/customization/calendar_builders.dart';
import 'package:table_calendar/src/customization/calendar_style.dart';
import 'package:table_calendar/src/customization/days_of_week_style.dart';
import 'package:table_calendar/src/customization/header_style.dart';
import 'package:table_calendar/src/shared/utils.dart';
import 'package:table_calendar/src/table_calendar_base.dart';
import 'package:table_calendar/src/widgets/calendar_header.dart';
import 'package:table_calendar/src/widgets/cell_content.dart';
/// Signature for `onDaySelected` callback. Contains the selected day and focused day.
typedef OnDaySelected = void Function(
DateTime selectedDay,
DateTime focusedDay,
);
/// Signature for `onRangeSelected` callback.
/// Contains start and end of the selected range, as well as currently focused day.
typedef OnRangeSelected = void Function(
DateTime? start,
DateTime? end,
DateTime focusedDay,
);
/// Modes that range selection can operate in.
enum RangeSelectionMode { disabled, toggledOff, toggledOn, enforced }
/// Highly customizable, feature-packed Flutter calendar with gestures, animations and multiple formats.
class TableCalendar<T> extends StatefulWidget {
/// Locale to format `TableCalendar` dates with, for example: `'en_US'`.
///
/// If nothing is provided, a default locale will be used.
final dynamic locale;
/// The start of the selected day range.
final DateTime? rangeStartDay;
/// The end of the selected day range.
final DateTime? rangeEndDay;
/// DateTime that determines which days are currently visible and focused.
final DateTime focusedDay;
/// The first active day of `TableCalendar`.
/// Blocks swiping to days before it.
///
/// Days before it will use `disabledStyle` and trigger `onDisabledDayTapped` callback.
final DateTime firstDay;
/// The last active day of `TableCalendar`.
/// Blocks swiping to days after it.
///
/// Days after it will use `disabledStyle` and trigger `onDisabledDayTapped` callback.
final DateTime lastDay;
/// DateTime that will be treated as today. Defaults to `DateTime.now()`.
///
/// Overriding this property might be useful for testing.
final DateTime? currentDay;
/// List of days treated as weekend days.
/// Use built-in `DateTime` weekday constants (e.g. `DateTime.monday`) instead of `int` literals (e.g. `1`).
final List<int> weekendDays;
/// Specifies `TableCalendar`'s current format.
final CalendarFormat calendarFormat;
/// `Map` of `CalendarFormat`s and `String` names associated with them.
/// Those `CalendarFormat`s will be used by internal logic to manage displayed format.
///
/// To ensure proper vertical swipe behavior, `CalendarFormat`s should be in descending order (i.e. from biggest to smallest).
///
/// For example:
/// ```dart
/// availableCalendarFormats: const {
/// CalendarFormat.month: 'Month',
/// CalendarFormat.week: 'Week',
/// }
/// ```
final Map<CalendarFormat, String> availableCalendarFormats;
/// Determines the visibility of calendar header.
final bool headerVisible;
/// Determines the visibility of the row of days of the week.
final bool daysOfWeekVisible;
/// When set to true, tapping on an outside day in `CalendarFormat.month` format
/// will jump to the calendar page of the tapped month.
final bool pageJumpingEnabled;
/// When set to true, updating the `focusedDay` will display a scrolling animation
/// if the currently visible calendar page is changed.
final bool pageAnimationEnabled;
/// When set to true, `CalendarFormat.month` will always display six weeks,
/// even if the content would fit in less.
final bool sixWeekMonthsEnforced;
/// When set to true, `TableCalendar` will fill available height.
final bool shouldFillViewport;
/// Whether to display week numbers on calendar.
final bool weekNumbersVisible;
/// Used for setting the height of `TableCalendar`'s rows.
final double rowHeight;
/// Used for setting the height of `TableCalendar`'s days of week row.
final double daysOfWeekHeight;
/// Specifies the duration of size animation that takes place whenever `calendarFormat` is changed.
final Duration formatAnimationDuration;
/// Specifies the curve of size animation that takes place whenever `calendarFormat` is changed.
final Curve formatAnimationCurve;
/// Specifies the duration of scrolling animation that takes place whenever the visible calendar page is changed.
final Duration pageAnimationDuration;
/// Specifies the curve of scrolling animation that takes place whenever the visible calendar page is changed.
final Curve pageAnimationCurve;
/// `TableCalendar` will start weeks with provided day.
///
/// Use `StartingDayOfWeek.monday` for Monday - Sunday week format.
/// Use `StartingDayOfWeek.sunday` for Sunday - Saturday week format.
final StartingDayOfWeek startingDayOfWeek;
/// `HitTestBehavior` for every day cell inside `TableCalendar`.
final HitTestBehavior dayHitTestBehavior;
/// Specifies swipe gestures available to `TableCalendar`.
/// If `AvailableGestures.none` is used, the calendar will only be interactive via buttons.
final AvailableGestures availableGestures;
/// Configuration for vertical swipe detector.
final SimpleSwipeConfig simpleSwipeConfig;
/// Style for `TableCalendar`'s header.
final HeaderStyle headerStyle;
/// Style for days of week displayed between `TableCalendar`'s header and content.
final DaysOfWeekStyle daysOfWeekStyle;
/// Style for `TableCalendar`'s content.
final CalendarStyle calendarStyle;
/// Set of custom builders for `TableCalendar` to work with.
/// Use those to fully tailor the UI.
final CalendarBuilders<T> calendarBuilders;
/// Current mode of range selection.
///
/// * `RangeSelectionMode.disabled` - range selection is always off.
/// * `RangeSelectionMode.toggledOff` - range selection is currently off, can be toggled by longpressing a day cell.
/// * `RangeSelectionMode.toggledOn` - range selection is currently on, can be toggled by longpressing a day cell.
/// * `RangeSelectionMode.enforced` - range selection is always on.
final RangeSelectionMode rangeSelectionMode;
/// Function that assigns a list of events to a specified day.
final List<T> Function(DateTime day)? eventLoader;
/// Function deciding whether given day should be enabled or not.
/// If `false` is returned, this day will be disabled.
final bool Function(DateTime day)? enabledDayPredicate;
/// Function deciding whether given day should be marked as selected.
final bool Function(DateTime day)? selectedDayPredicate;
/// Function deciding whether given day is treated as a holiday.
final bool Function(DateTime day)? holidayPredicate;
/// Called whenever a day range gets selected.
final OnRangeSelected? onRangeSelected;
/// Called whenever any day gets tapped.
final OnDaySelected? onDaySelected;
/// Called whenever any day gets long pressed.
final OnDaySelected? onDayLongPressed;
/// Called whenever any disabled day gets tapped.
final void Function(DateTime day)? onDisabledDayTapped;
/// Called whenever any disabled day gets long pressed.
final void Function(DateTime day)? onDisabledDayLongPressed;
/// Called whenever header gets tapped.
final void Function(DateTime focusedDay)? onHeaderTapped;
/// Called whenever header gets long pressed.
final void Function(DateTime focusedDay)? onHeaderLongPressed;
/// Called whenever currently visible calendar page is changed.
final void Function(DateTime focusedDay)? onPageChanged;
/// Called whenever `calendarFormat` is changed.
final void Function(CalendarFormat format)? onFormatChanged;
/// Called when the calendar is created. Exposes its PageController.
final void Function(PageController pageController)? onCalendarCreated;
/// Creates a `TableCalendar` widget.
TableCalendar({
super.key,
required DateTime focusedDay,
required DateTime firstDay,
required DateTime lastDay,
DateTime? currentDay,
this.locale,
this.rangeStartDay,
this.rangeEndDay,
this.weekendDays = const [DateTime.saturday, DateTime.sunday],
this.calendarFormat = CalendarFormat.month,
this.availableCalendarFormats = const {
CalendarFormat.month: 'Month',
CalendarFormat.twoWeeks: '2 weeks',
CalendarFormat.week: 'Week',
},
this.headerVisible = true,
this.daysOfWeekVisible = true,
this.pageJumpingEnabled = false,
this.pageAnimationEnabled = true,
this.sixWeekMonthsEnforced = false,
this.shouldFillViewport = false,
this.weekNumbersVisible = false,
this.rowHeight = 52.0,
this.daysOfWeekHeight = 16.0,
this.formatAnimationDuration = const Duration(milliseconds: 200),
this.formatAnimationCurve = Curves.linear,
this.pageAnimationDuration = const Duration(milliseconds: 300),
this.pageAnimationCurve = Curves.easeOut,
this.startingDayOfWeek = StartingDayOfWeek.sunday,
this.dayHitTestBehavior = HitTestBehavior.opaque,
this.availableGestures = AvailableGestures.all,
this.simpleSwipeConfig = const SimpleSwipeConfig(
verticalThreshold: 25.0,
swipeDetectionBehavior: SwipeDetectionBehavior.continuousDistinct,
),
this.headerStyle = const HeaderStyle(),
this.daysOfWeekStyle = const DaysOfWeekStyle(),
this.calendarStyle = const CalendarStyle(),
this.calendarBuilders = const CalendarBuilders(),
this.rangeSelectionMode = RangeSelectionMode.toggledOff,
this.eventLoader,
this.enabledDayPredicate,
this.selectedDayPredicate,
this.holidayPredicate,
this.onRangeSelected,
this.onDaySelected,
this.onDayLongPressed,
this.onDisabledDayTapped,
this.onDisabledDayLongPressed,
this.onHeaderTapped,
this.onHeaderLongPressed,
this.onPageChanged,
this.onFormatChanged,
this.onCalendarCreated,
}) : assert(availableCalendarFormats.keys.contains(calendarFormat)),
assert(availableCalendarFormats.length <= CalendarFormat.values.length),
assert(
weekendDays.isNotEmpty &&
weekendDays.every(
(day) => day >= DateTime.monday && day <= DateTime.sunday,
),
),
focusedDay = normalizeDate(focusedDay),
firstDay = normalizeDate(firstDay),
lastDay = normalizeDate(lastDay),
currentDay = currentDay ?? DateTime.now();
@override
State<TableCalendar<T>> createState() => _TableCalendarState<T>();
}
class _TableCalendarState<T> extends State<TableCalendar<T>> {
late final PageController _pageController;
late final ValueNotifier<DateTime> _focusedDay;
late RangeSelectionMode _rangeSelectionMode;
DateTime? _firstSelectedDay;
@override
void initState() {
super.initState();
_focusedDay = ValueNotifier(widget.focusedDay);
_rangeSelectionMode = widget.rangeSelectionMode;
}
@override
void didUpdateWidget(TableCalendar<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (_focusedDay.value != widget.focusedDay) {
_focusedDay.value = widget.focusedDay;
}
if (_rangeSelectionMode != widget.rangeSelectionMode) {
_rangeSelectionMode = widget.rangeSelectionMode;
}
if (widget.rangeStartDay == null && widget.rangeEndDay == null) {
_firstSelectedDay = null;
}
}
@override
void dispose() {
_focusedDay.dispose();
super.dispose();
}
bool get _isRangeSelectionToggleable =>
_rangeSelectionMode == RangeSelectionMode.toggledOn ||
_rangeSelectionMode == RangeSelectionMode.toggledOff;
bool get _isRangeSelectionOn =>
_rangeSelectionMode == RangeSelectionMode.toggledOn ||
_rangeSelectionMode == RangeSelectionMode.enforced;
bool get _shouldBlockOutsideDays =>
!widget.calendarStyle.outsideDaysVisible &&
widget.calendarFormat == CalendarFormat.month;
void _swipeCalendarFormat(SwipeDirection direction) {
if (widget.onFormatChanged != null) {
final formats = widget.availableCalendarFormats.keys.toList();
final isSwipeUp = direction == SwipeDirection.up;
int id = formats.indexOf(widget.calendarFormat);
// Order of CalendarFormats must be from biggest to smallest,
// e.g.: [month, twoWeeks, week]
if (isSwipeUp) {
id = min(formats.length - 1, id + 1);
} else {
id = max(0, id - 1);
}
widget.onFormatChanged!(formats[id]);
}
}
void _onDayTapped(DateTime day) {
final isOutside = day.month != _focusedDay.value.month;
if (isOutside && _shouldBlockOutsideDays) {
return;
}
if (_isDayDisabled(day)) {
return widget.onDisabledDayTapped?.call(day);
}
_updateFocusOnTap(day);
if (_isRangeSelectionOn && widget.onRangeSelected != null) {
if (_firstSelectedDay == null) {
_firstSelectedDay = day;
widget.onRangeSelected!(_firstSelectedDay, null, _focusedDay.value);
} else {
if (day.isAfter(_firstSelectedDay!)) {
widget.onRangeSelected!(_firstSelectedDay, day, _focusedDay.value);
_firstSelectedDay = null;
} else if (day.isBefore(_firstSelectedDay!)) {
widget.onRangeSelected!(day, _firstSelectedDay, _focusedDay.value);
_firstSelectedDay = null;
}
}
} else {
widget.onDaySelected?.call(day, _focusedDay.value);
}
}
void _onDayLongPressed(DateTime day) {
final isOutside = day.month != _focusedDay.value.month;
if (isOutside && _shouldBlockOutsideDays) {
return;
}
if (_isDayDisabled(day)) {
return widget.onDisabledDayLongPressed?.call(day);
}
if (widget.onDayLongPressed != null) {
_updateFocusOnTap(day);
return widget.onDayLongPressed!(day, _focusedDay.value);
}
if (widget.onRangeSelected != null) {
if (_isRangeSelectionToggleable) {
_updateFocusOnTap(day);
_toggleRangeSelection();
if (_isRangeSelectionOn) {
_firstSelectedDay = day;
widget.onRangeSelected!(_firstSelectedDay, null, _focusedDay.value);
} else {
_firstSelectedDay = null;
widget.onDaySelected?.call(day, _focusedDay.value);
}
}
}
}
void _updateFocusOnTapJumpYear(DateTime day) {
if (widget.pageJumpingEnabled) {
_focusedDay.value = day;
return;
}
if (widget.calendarFormat == CalendarFormat.month) {
if (_isBeforeYear(day, _focusedDay.value)) {
_focusedDay.value = _firstDayOfMonth(day);
} else if (_isAfterYear(day, _focusedDay.value)) {
_focusedDay.value = _lastDayOfMonth(day);
} else {
_focusedDay.value = day;
}
} else {
_focusedDay.value = day;
}
}
void _updateFocusOnTap(DateTime day) {
if (widget.pageJumpingEnabled) {
_focusedDay.value = day;
return;
}
if (widget.calendarFormat == CalendarFormat.month) {
if (_isBeforeMonth(day, _focusedDay.value)) {
_focusedDay.value = _firstDayOfMonth(_focusedDay.value);
} else if (_isAfterMonth(day, _focusedDay.value)) {
_focusedDay.value = _lastDayOfMonth(_focusedDay.value);
} else {
_focusedDay.value = day;
}
} else {
_focusedDay.value = day;
}
}
void _toggleRangeSelection() {
if (_rangeSelectionMode == RangeSelectionMode.toggledOn) {
_rangeSelectionMode = RangeSelectionMode.toggledOff;
} else {
_rangeSelectionMode = RangeSelectionMode.toggledOn;
}
}
void _onLeftChevronTap() {
_pageController.previousPage(
duration: widget.pageAnimationDuration,
curve: widget.pageAnimationCurve,
);
}
void _selectPreviousYear() {
DateTime focusedDay = DateTime(
_focusedDay.value.year - 1,
_focusedDay.value.month,
_focusedDay.value.day,
);
_updateFocusOnTapJumpYear(focusedDay);
widget.onPageChanged?.call(focusedDay);
_pageController.previousPage(
duration: widget.pageAnimationDuration,
curve: widget.pageAnimationCurve,
);
}
void _selectNextYear() {
DateTime focusedDay = DateTime(
_focusedDay.value.year + 1,
_focusedDay.value.month,
_focusedDay.value.day,
);
// _focusedDay.value = focusedDay;
_updateFocusOnTapJumpYear(focusedDay);
widget.onPageChanged?.call(focusedDay);
}
void _onRightChevronTap() {
_pageController.nextPage(
duration: widget.pageAnimationDuration,
curve: widget.pageAnimationCurve,
);
}
@override
Widget build(BuildContext context) {
return Column(
children: [
if (widget.headerVisible)
ValueListenableBuilder<DateTime>(
valueListenable: _focusedDay,
builder: (context, value, _) {
return CalendarHeader(
headerTitleBuilder: widget.calendarBuilders.headerTitleBuilder,
focusedMonth: value,
onLeftChevronTap: _onLeftChevronTap,
onRightChevronTap: _onRightChevronTap,
onHeaderTap: () => widget.onHeaderTapped?.call(value),
onHeaderLongPress: () =>
widget.onHeaderLongPressed?.call(value),
headerStyle: widget.headerStyle,
availableCalendarFormats: widget.availableCalendarFormats,
calendarFormat: widget.calendarFormat,
locale: widget.locale,
onFormatButtonTap: (format) {
assert(
widget.onFormatChanged != null,
'Using `FormatButton` without providing `onFormatChanged` will have no effect.',
);
widget.onFormatChanged?.call(format);
},
selectPreviousYear: _selectPreviousYear,
selectNextYear: _selectNextYear,
);
},
),
ValueListenableBuilder<DateTime>(
valueListenable: _focusedDay,
builder: (context, value, _) {
return Flexible(
flex: widget.shouldFillViewport ? 1 : 0,
child: TableCalendarBase(
onCalendarCreated: (pageController) {
_pageController = pageController;
widget.onCalendarCreated?.call(pageController);
},
focusedDay: _focusedDay.value,
calendarFormat: widget.calendarFormat,
availableGestures: widget.availableGestures,
firstDay: widget.firstDay,
lastDay: widget.lastDay,
startingDayOfWeek: widget.startingDayOfWeek,
dowDecoration: widget.daysOfWeekStyle.decoration,
rowDecoration: widget.calendarStyle.rowDecoration,
tableBorder: widget.calendarStyle.tableBorder,
tablePadding: widget.calendarStyle.tablePadding,
dowVisible: widget.daysOfWeekVisible,
dowHeight: widget.daysOfWeekHeight,
rowHeight: widget.rowHeight,
formatAnimationDuration: widget.formatAnimationDuration,
formatAnimationCurve: widget.formatAnimationCurve,
pageAnimationEnabled: widget.pageAnimationEnabled,
pageAnimationDuration: widget.pageAnimationDuration,
pageAnimationCurve: widget.pageAnimationCurve,
availableCalendarFormats: widget.availableCalendarFormats,
simpleSwipeConfig: widget.simpleSwipeConfig,
sixWeekMonthsEnforced: widget.sixWeekMonthsEnforced,
onVerticalSwipe: _swipeCalendarFormat,
onPageChanged: (focusedDay) {
_focusedDay.value = focusedDay;
widget.onPageChanged?.call(focusedDay);
},
weekNumbersVisible: widget.weekNumbersVisible,
weekNumberBuilder: (BuildContext context, DateTime day) {
final weekNumber = _calculateWeekNumber(day);
final cell = widget.calendarBuilders.weekNumberBuilder
?.call(context, weekNumber);
return cell ??
Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Center(
child: Text(
weekNumber.toString(),
style: widget.calendarStyle.weekNumberTextStyle,
),
),
);
},
dowBuilder: (BuildContext context, DateTime day) {
Widget? dowCell =
widget.calendarBuilders.dowBuilder?.call(context, day);
if (dowCell == null) {
final weekdayString = widget
.daysOfWeekStyle.dowTextFormatter
?.call(day, widget.locale) ??
DateFormat.E(widget.locale).format(day);
final isWeekend =
_isWeekend(day, weekendDays: widget.weekendDays);
dowCell = Center(
child: ExcludeSemantics(
child: Text(
weekdayString,
style: isWeekend
? widget.daysOfWeekStyle.weekendStyle
: widget.daysOfWeekStyle.weekdayStyle,
),
),
);
}
return dowCell;
},
dayBuilder: (context, day, focusedMonth) {
return GestureDetector(
behavior: widget.dayHitTestBehavior,
onTap: () => _onDayTapped(day),
onLongPress: () => _onDayLongPressed(day),
child: _buildCell(day, focusedMonth),
);
},
),
);
}),
],
);
}
Widget _buildCell(DateTime day, DateTime focusedDay) {
final isOutside = day.month != focusedDay.month;
if (isOutside && _shouldBlockOutsideDays) {
return Container();
}
return LayoutBuilder(
builder: (context, constraints) {
final shorterSide = constraints.maxHeight > constraints.maxWidth
? constraints.maxWidth
: constraints.maxHeight;
final children = <Widget>[];
final isWithinRange = widget.rangeStartDay != null &&
widget.rangeEndDay != null &&
_isWithinRange(day, widget.rangeStartDay!, widget.rangeEndDay!);
final isRangeStart = isSameDay(day, widget.rangeStartDay);
final isRangeEnd = isSameDay(day, widget.rangeEndDay);
Widget? rangeHighlight = widget.calendarBuilders.rangeHighlightBuilder
?.call(context, day, isWithinRange);
if (rangeHighlight == null) {
if (isWithinRange) {
rangeHighlight = Center(
child: Container(
margin: EdgeInsetsDirectional.only(
start: isRangeStart ? constraints.maxWidth * 0.5 : 0.0,
end: isRangeEnd ? constraints.maxWidth * 0.5 : 0.0,
),
height:
(shorterSide - widget.calendarStyle.cellMargin.vertical) *
widget.calendarStyle.rangeHighlightScale,
color: widget.calendarStyle.rangeHighlightColor,
),
);
}
}
if (rangeHighlight != null) {
children.add(rangeHighlight);
}
final isToday = isSameDay(day, widget.currentDay);
final isDisabled = _isDayDisabled(day);
final isWeekend = _isWeekend(day, weekendDays: widget.weekendDays);
final content = CellContent(
key: ValueKey('CellContent-${day.year}-${day.month}-${day.day}'),
day: day,
focusedDay: focusedDay,
calendarStyle: widget.calendarStyle,
calendarBuilders: widget.calendarBuilders,
isTodayHighlighted: widget.calendarStyle.isTodayHighlighted,
isToday: isToday,
isSelected: widget.selectedDayPredicate?.call(day) ?? false,
isRangeStart: isRangeStart,
isRangeEnd: isRangeEnd,
isWithinRange: isWithinRange,
isOutside: isOutside,
isDisabled: isDisabled,
isWeekend: isWeekend,
isHoliday: widget.holidayPredicate?.call(day) ?? false,
locale: widget.locale,
);
children.add(content);
if (!isDisabled) {
final events = widget.eventLoader?.call(day) ?? [];
Widget? markerWidget =
widget.calendarBuilders.markerBuilder?.call(context, day, events);
if (events.isNotEmpty && markerWidget == null) {
final center = constraints.maxHeight / 2;
final markerSize = widget.calendarStyle.markerSize ??
(shorterSide - widget.calendarStyle.cellMargin.vertical) *
widget.calendarStyle.markerSizeScale;
final markerAutoAlignmentTop = center +
(shorterSide - widget.calendarStyle.cellMargin.vertical) / 2 -
(markerSize * widget.calendarStyle.markersAnchor);
markerWidget = PositionedDirectional(
top: widget.calendarStyle.markersAutoAligned
? markerAutoAlignmentTop
: widget.calendarStyle.markersOffset.top,
bottom: widget.calendarStyle.markersAutoAligned
? null
: widget.calendarStyle.markersOffset.bottom,
start: widget.calendarStyle.markersAutoAligned
? null
: widget.calendarStyle.markersOffset.start,
end: widget.calendarStyle.markersAutoAligned
? null
: widget.calendarStyle.markersOffset.end,
child: Row(
mainAxisSize: MainAxisSize.min,
children: events
.take(widget.calendarStyle.markersMaxCount)
.map((event) => _buildSingleMarker(day, event, markerSize))
.toList(),
),
);
}
if (markerWidget != null) {
children.add(markerWidget);
}
}
return Stack(
alignment: widget.calendarStyle.markersAlignment,
clipBehavior: widget.calendarStyle.canMarkersOverflow
? Clip.none
: Clip.hardEdge,
children: children,
);
},
);
}
Widget _buildSingleMarker(DateTime day, T event, double markerSize) {
return widget.calendarBuilders.singleMarkerBuilder
?.call(context, day, event) ??
Container(
width: markerSize,
height: markerSize,
margin: widget.calendarStyle.markerMargin,
decoration: widget.calendarStyle.markerDecoration,
);
}
int _calculateWeekNumber(DateTime date) {
final middleDay = date.add(const Duration(days: 3));
final dayOfYear = _dayOfYear(middleDay);
return 1 + ((dayOfYear - 1) / 7).floor();
}
int _dayOfYear(DateTime date) {
return normalizeDate(date).difference(DateTime.utc(date.year)).inDays + 1;
}
bool _isWithinRange(DateTime day, DateTime start, DateTime end) {
if (isSameDay(day, start) || isSameDay(day, end)) {
return true;
}
if (day.isAfter(start) && day.isBefore(end)) {
return true;
}
return false;
}
bool _isDayDisabled(DateTime day) {
return day.isBefore(widget.firstDay) ||
day.isAfter(widget.lastDay) ||
!_isDayAvailable(day);
}
bool _isDayAvailable(DateTime day) {
if (widget.enabledDayPredicate == null) {
return true;
}
return widget.enabledDayPredicate!(day);
}
DateTime _firstDayOfMonth(DateTime month) {
return DateTime.utc(month.year, month.month);
}
DateTime _lastDayOfMonth(DateTime month) {
final date = month.month < 12
? DateTime.utc(month.year, month.month + 1)
: DateTime.utc(month.year + 1);
return date.subtract(const Duration(days: 1));
}
bool _isBeforeMonth(DateTime day, DateTime month) {
if (day.year == month.year) {
return day.month < month.month;
} else {
return day.isBefore(month);
}
}
bool _isAfterMonth(DateTime day, DateTime month) {
if (day.year == month.year) {
return day.month > month.month;
} else {
return day.isAfter(month);
}
}
bool _isBeforeYear(DateTime day, DateTime month) {
if (day.year == month.year) {
return day.month < month.month;
} else {
return day.isBefore(month);
}
}
bool _isAfterYear(DateTime day, DateTime month) {
if (day.year == month.year) {
return day.month > month.month;
} else {
return day.isAfter(month);
}
}
bool _isWeekend(
DateTime day, {
List<int> weekendDays = const [DateTime.saturday, DateTime.sunday],
}) {
return weekendDays.contains(day.weekday);
}
}