-
Notifications
You must be signed in to change notification settings - Fork 33.1k
Expand file tree
/
Copy pathdate_picker.dart
More file actions
3493 lines (3160 loc) · 127 KB
/
Copy pathdate_picker.dart
File metadata and controls
3493 lines (3160 loc) · 127 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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'dart:ui';
///
/// @docImport 'app.dart';
/// @docImport 'time_picker.dart';
library;
import 'dart:math' as math;
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'app_bar.dart';
import 'back_button.dart';
import 'button_style.dart';
import 'calendar_date_picker.dart';
import 'color_scheme.dart';
import 'date.dart';
import 'date_picker_theme.dart';
import 'debug.dart';
import 'dialog.dart';
import 'dialog_theme.dart';
import 'divider.dart';
import 'icon_button.dart';
import 'icons.dart';
import 'ink_well.dart';
import 'input_border.dart';
import 'input_date_picker_form_field.dart';
import 'input_decorator.dart';
import 'material.dart';
import 'material_localizations.dart';
import 'scaffold.dart';
import 'text_button.dart';
import 'text_field.dart';
import 'text_theme.dart';
import 'theme.dart';
// The M3 sizes are coming from the tokens, but are hand coded,
// as the current token DB does not contain landscape versions.
const Size _calendarPortraitDialogSizeM2 = Size(330.0, 518.0);
const Size _calendarPortraitDialogSizeM3 = Size(360.0, 568.0);
const Size _calendarLandscapeDialogSize = Size(496.0, 346.0);
const Size _inputPortraitDialogSizeM2 = Size(330.0, 270.0);
const Size _inputPortraitDialogSizeM3 = Size(328.0, 270.0);
const Size _inputLandscapeDialogSize = Size(496, 160.0);
const Size _inputRangeLandscapeDialogSize = Size(496, 164.0);
const Duration _dialogSizeAnimationDuration = Duration(milliseconds: 200);
const double _inputFormPortraitHeight = 98.0;
const double _inputFormLandscapeHeight = 108.0;
// 3.0 is the maximum scale factor on mobile phones. As of 07/30/24, iOS goes up
// to a max of 3.0 text scale factor, and Android goes up to 2.0. This is the
// default used for non-range date pickers. This default is changed to a lower
// value at different parts of the date pickers depending on content, and device
// orientation.
const double _kMaxTextScaleFactor = 3.0;
// The max scale factor for the date range pickers.
const double _kMaxRangeTextScaleFactor = 1.3;
// The max text scale factor for the header. This is lower than the default as
// the title text already starts at a large size.
const double _kMaxHeaderTextScaleFactor = 1.6;
// The entry button shares a line with the header text, so there is less room to
// scale up.
const double _kMaxHeaderWithEntryTextScaleFactor = 1.4;
const double _kMaxHelpPortraitTextScaleFactor = 1.6;
const double _kMaxHelpLandscapeTextScaleFactor = 1.4;
// 14 is a common font size used to compute the effective text scale.
const double _fontSizeToScale = 14.0;
/// Shows a dialog containing a Material Design date picker.
///
/// The returned [Future] resolves to the date selected by the user when the
/// user confirms the dialog. If the user cancels the dialog, null is returned.
///
/// When the date picker is first displayed, if [initialDate] is not null, it
/// will show the month of [initialDate], with [initialDate] selected. Otherwise
/// it will show the [currentDate]'s month.
///
/// The [firstDate] is the earliest allowable date. The [lastDate] is the latest
/// allowable date. If [initialDate] is not null, it must either fall between
/// these dates, or be equal to one of them. For each of these [DateTime]
/// parameters, only their dates are considered. Their time fields are ignored.
/// They must all be non-null.
///
/// The [currentDate] represents the current day (i.e. today). This
/// date will be highlighted in the day grid. If null, the date of
/// [DateTime.now] will be used.
///
/// An optional [initialEntryMode] argument can be used to display the date
/// picker in the [DatePickerEntryMode.calendar] (a calendar month grid)
/// or [DatePickerEntryMode.input] (a text input field) mode.
/// It defaults to [DatePickerEntryMode.calendar].
///
/// {@template flutter.material.date_picker.switchToInputEntryModeIcon}
/// An optional [switchToInputEntryModeIcon] argument can be used to
/// display a custom Icon in the corner of the dialog
/// when [DatePickerEntryMode] is [DatePickerEntryMode.calendar]. Clicking on
/// icon changes the [DatePickerEntryMode] to [DatePickerEntryMode.input].
/// If null, `Icon(useMaterial3 ? Icons.edit_outlined : Icons.edit)` is used.
/// {@endtemplate}
///
/// {@template flutter.material.date_picker.switchToCalendarEntryModeIcon}
/// An optional [switchToCalendarEntryModeIcon] argument can be used to
/// display a custom Icon in the corner of the dialog
/// when [DatePickerEntryMode] is [DatePickerEntryMode.input]. Clicking on
/// icon changes the [DatePickerEntryMode] to [DatePickerEntryMode.calendar].
/// If null, `Icon(Icons.calendar_today)` is used.
/// {@endtemplate}
///
/// An optional [selectableDayPredicate] function can be passed in to only allow
/// certain days for selection. If provided, only the days that
/// [selectableDayPredicate] returns true for will be selectable. For example,
/// this can be used to only allow weekdays for selection. If provided, it must
/// return true for [initialDate].
///
/// {@macro flutter.material.calendar_date_picker.calendarDelegate}
///
/// The following optional string parameters allow you to override the default
/// text used for various parts of the dialog:
///
/// * [helpText], label displayed at the top of the dialog.
/// * [cancelText], label on the cancel button.
/// * [confirmText], label on the ok button.
/// * [errorFormatText], message used when the input text isn't in a proper date format.
/// * [errorInvalidText], message used when the input text isn't a selectable date.
/// * [fieldHintText], text used to prompt the user when no text has been entered in the field.
/// * [fieldLabelText], label for the date text input field.
///
/// An optional [locale] argument can be used to set the locale for the date
/// picker. It defaults to the ambient locale provided by [Localizations].
///
/// An optional [textDirection] argument can be used to set the text direction
/// ([TextDirection.ltr] or [TextDirection.rtl]) for the date picker. It
/// defaults to the ambient text direction provided by [Directionality]. If both
/// [locale] and [textDirection] are non-null, [textDirection] overrides the
/// direction chosen for the [locale].
///
/// The [context], [barrierDismissible], [barrierColor], [barrierLabel],
/// [useRootNavigator] and [routeSettings] arguments are passed to [showDialog],
/// the documentation for which discusses how it is used.
///
/// The [builder] parameter can be used to wrap the dialog widget
/// to add inherited widgets like [Theme].
///
/// An optional [initialDatePickerMode] argument can be used to have the
/// calendar date picker initially appear in the [DatePickerMode.year] or
/// [DatePickerMode.day] mode. It defaults to [DatePickerMode.day].
///
/// {@macro flutter.widgets.RawDialogRoute}
///
/// {@tool dartpad}
/// This sample demonstrates how to create a basic date picker.
/// Tapping the button displays a date picker which returns the selected date.
///
/// ** See code in examples/api/lib/material/date_picker/show_date_picker.1.dart **
/// {@end-tool}
///
/// ### State Restoration
///
/// Using this method will not enable state restoration for the date picker.
/// In order to enable state restoration for a date picker, use
/// [Navigator.restorablePush] or [Navigator.restorablePushNamed] with
/// [DatePickerDialog].
///
/// For more information about state restoration, see [RestorationManager].
///
/// {@macro flutter.widgets.RestorationManager}
///
/// {@tool dartpad}
/// This sample demonstrates how to create a restorable Material date picker.
/// This is accomplished by enabling state restoration by specifying
/// [MaterialApp.restorationScopeId] and using [Navigator.restorablePush] to
/// push [DatePickerDialog] when the button is tapped.
///
/// ** See code in examples/api/lib/material/date_picker/show_date_picker.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [showDateRangePicker], which shows a Material Design date range picker
/// used to select a range of dates.
/// * [CalendarDatePicker], which provides the calendar grid used by the date picker dialog.
/// * [InputDatePickerFormField], which provides a text input field for entering dates.
/// * [DisplayFeatureSubScreen], which documents the specifics of how
/// [DisplayFeature]s can split the screen into sub-screens.
/// * [showTimePicker], which shows a dialog that contains a Material Design time picker.
Future<DateTime?> showDatePicker({
required BuildContext context,
DateTime? initialDate,
required DateTime firstDate,
required DateTime lastDate,
DateTime? currentDate,
DatePickerEntryMode initialEntryMode = DatePickerEntryMode.calendar,
SelectableDayPredicate? selectableDayPredicate,
String? helpText,
String? cancelText,
String? confirmText,
Locale? locale,
bool barrierDismissible = true,
Color? barrierColor,
String? barrierLabel,
bool useRootNavigator = true,
RouteSettings? routeSettings,
TextDirection? textDirection,
TransitionBuilder? builder,
DatePickerMode initialDatePickerMode = DatePickerMode.day,
String? errorFormatText,
String? errorInvalidText,
String? fieldHintText,
String? fieldLabelText,
TextInputType? keyboardType,
Offset? anchorPoint,
ValueChanged<DatePickerEntryMode>? onDatePickerModeChange,
Icon? switchToInputEntryModeIcon,
Icon? switchToCalendarEntryModeIcon,
CalendarDelegate<DateTime> calendarDelegate = const GregorianCalendarDelegate(),
}) async {
initialDate = initialDate == null ? null : calendarDelegate.dateOnly(initialDate);
firstDate = calendarDelegate.dateOnly(firstDate);
lastDate = calendarDelegate.dateOnly(lastDate);
assert(
!lastDate.isBefore(firstDate),
'lastDate $lastDate must be on or after firstDate $firstDate.',
);
assert(
initialDate == null || !initialDate.isBefore(firstDate),
'initialDate $initialDate must be on or after firstDate $firstDate.',
);
assert(
initialDate == null || !initialDate.isAfter(lastDate),
'initialDate $initialDate must be on or before lastDate $lastDate.',
);
assert(
selectableDayPredicate == null || initialDate == null || selectableDayPredicate(initialDate),
'Provided initialDate $initialDate must satisfy provided selectableDayPredicate.',
);
assert(debugCheckHasMaterialLocalizations(context));
Widget dialog = DatePickerDialog(
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
currentDate: currentDate,
initialEntryMode: initialEntryMode,
selectableDayPredicate: selectableDayPredicate,
helpText: helpText,
cancelText: cancelText,
confirmText: confirmText,
initialCalendarMode: initialDatePickerMode,
errorFormatText: errorFormatText,
errorInvalidText: errorInvalidText,
fieldHintText: fieldHintText,
fieldLabelText: fieldLabelText,
keyboardType: keyboardType,
onDatePickerModeChange: onDatePickerModeChange,
switchToInputEntryModeIcon: switchToInputEntryModeIcon,
switchToCalendarEntryModeIcon: switchToCalendarEntryModeIcon,
calendarDelegate: calendarDelegate,
);
if (textDirection != null) {
dialog = Directionality(textDirection: textDirection, child: dialog);
}
if (locale != null) {
dialog = Localizations.override(context: context, locale: locale, child: dialog);
} else {
final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context);
if (datePickerTheme.locale != null) {
dialog = Localizations.override(
context: context,
locale: datePickerTheme.locale,
child: dialog,
);
}
}
return showDialog<DateTime>(
context: context,
barrierDismissible: barrierDismissible,
barrierColor: barrierColor,
barrierLabel: barrierLabel,
useRootNavigator: useRootNavigator,
routeSettings: routeSettings,
builder: (BuildContext context) {
return builder == null ? dialog : builder(context, dialog);
},
anchorPoint: anchorPoint,
);
}
/// A Material-style date picker dialog.
///
/// It is used internally by [showDatePicker] or can be directly pushed
/// onto the [Navigator] stack to enable state restoration. See
/// [showDatePicker] for a state restoration app example.
///
/// See also:
///
/// * [showDatePicker], which is a way to display the date picker.
class DatePickerDialog extends StatefulWidget {
/// A Material-style date picker dialog.
DatePickerDialog({
super.key,
DateTime? initialDate,
required DateTime firstDate,
required DateTime lastDate,
DateTime? currentDate,
this.initialEntryMode = DatePickerEntryMode.calendar,
this.selectableDayPredicate,
this.cancelText,
this.confirmText,
this.helpText,
this.initialCalendarMode = DatePickerMode.day,
this.errorFormatText,
this.errorInvalidText,
this.fieldHintText,
this.fieldLabelText,
this.keyboardType,
this.restorationId,
this.onDatePickerModeChange,
this.switchToInputEntryModeIcon,
this.switchToCalendarEntryModeIcon,
this.insetPadding = const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0),
this.calendarDelegate = const GregorianCalendarDelegate(),
}) : initialDate = initialDate == null ? null : calendarDelegate.dateOnly(initialDate),
firstDate = calendarDelegate.dateOnly(firstDate),
lastDate = calendarDelegate.dateOnly(lastDate),
currentDate = calendarDelegate.dateOnly(currentDate ?? calendarDelegate.now()) {
assert(
!this.lastDate.isBefore(this.firstDate),
'lastDate ${this.lastDate} must be on or after firstDate ${this.firstDate}.',
);
assert(
initialDate == null || !this.initialDate!.isBefore(this.firstDate),
'initialDate ${this.initialDate} must be on or after firstDate ${this.firstDate}.',
);
assert(
initialDate == null || !this.initialDate!.isAfter(this.lastDate),
'initialDate ${this.initialDate} must be on or before lastDate ${this.lastDate}.',
);
assert(
selectableDayPredicate == null ||
initialDate == null ||
selectableDayPredicate!(this.initialDate!),
'Provided initialDate ${this.initialDate} must satisfy provided selectableDayPredicate',
);
}
/// The initially selected [DateTime] that the picker should display.
///
/// If this is null, there is no selected date. A date must be selected to
/// submit the dialog.
final DateTime? initialDate;
/// The earliest allowable [DateTime] that the user can select.
final DateTime firstDate;
/// The latest allowable [DateTime] that the user can select.
final DateTime lastDate;
/// The [DateTime] representing today. It will be highlighted in the day grid.
final DateTime currentDate;
/// The initial mode of date entry method for the date picker dialog.
///
/// See [DatePickerEntryMode] for more details on the different data entry
/// modes available.
final DatePickerEntryMode initialEntryMode;
/// Function to provide full control over which [DateTime] can be selected.
final SelectableDayPredicate? selectableDayPredicate;
/// The text that is displayed on the cancel button.
final String? cancelText;
/// The text that is displayed on the confirm button.
final String? confirmText;
/// The text that is displayed at the top of the header.
///
/// This is used to indicate to the user what they are selecting a date for.
final String? helpText;
/// The initial display of the calendar picker.
final DatePickerMode initialCalendarMode;
/// The error text displayed if the entered date is not in the correct format.
final String? errorFormatText;
/// The error text displayed if the date is not valid.
///
/// A date is not valid if it is earlier than [firstDate], later than
/// [lastDate], or doesn't pass the [selectableDayPredicate].
final String? errorInvalidText;
/// The hint text displayed in the [TextField].
///
/// If this is null, it will default to the date format string. For example,
/// 'mm/dd/yyyy' for en_US.
final String? fieldHintText;
/// The label text displayed in the [TextField].
///
/// If this is null, it will default to the words representing the date format
/// string. For example, 'Month, Day, Year' for en_US.
final String? fieldLabelText;
/// {@template flutter.material.datePickerDialog}
/// The keyboard type of the [TextField].
///
/// If this is null, it will default to [TextInputType.datetime]
/// {@endtemplate}
final TextInputType? keyboardType;
/// Restoration ID to save and restore the state of the [DatePickerDialog].
///
/// If it is non-null, the date picker will persist and restore the
/// date selected on the dialog.
///
/// The state of this widget is persisted in a [RestorationBucket] claimed
/// from the surrounding [RestorationScope] using the provided restoration ID.
///
/// See also:
///
/// * [RestorationManager], which explains how state restoration works in
/// Flutter.
final String? restorationId;
/// Called when the [DatePickerDialog] is toggled between
/// [DatePickerEntryMode.calendar],[DatePickerEntryMode.input].
///
/// An example of how this callback might be used is an app that saves the
/// user's preferred entry mode and uses it to initialize the
/// `initialEntryMode` parameter the next time the date picker is shown.
final ValueChanged<DatePickerEntryMode>? onDatePickerModeChange;
/// {@macro flutter.material.date_picker.switchToInputEntryModeIcon}
final Icon? switchToInputEntryModeIcon;
/// {@macro flutter.material.date_picker.switchToCalendarEntryModeIcon}
final Icon? switchToCalendarEntryModeIcon;
/// The amount of padding added to [MediaQueryData.viewInsets] on the outside
/// of the dialog. This defines the minimum space between the screen's edges
/// and the dialog.
///
/// Defaults to `EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0)`.
final EdgeInsets insetPadding;
/// {@macro flutter.material.calendar_date_picker.calendarDelegate}
final CalendarDelegate<DateTime> calendarDelegate;
@override
State<DatePickerDialog> createState() => _DatePickerDialogState();
}
class _DatePickerDialogState extends State<DatePickerDialog> with RestorationMixin {
late final RestorableDateTimeN _selectedDate = RestorableDateTimeN(widget.initialDate);
late final _RestorableDatePickerEntryMode _entryMode = _RestorableDatePickerEntryMode(
widget.initialEntryMode,
);
final _RestorableAutovalidateMode _autovalidateMode = _RestorableAutovalidateMode(
AutovalidateMode.disabled,
);
@override
void dispose() {
_selectedDate.dispose();
_entryMode.dispose();
_autovalidateMode.dispose();
super.dispose();
}
@override
String? get restorationId => widget.restorationId;
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_selectedDate, 'selected_date');
registerForRestoration(_autovalidateMode, 'autovalidateMode');
registerForRestoration(_entryMode, 'calendar_entry_mode');
}
final GlobalKey _calendarPickerKey = GlobalKey();
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
void _handleOk() {
if (_entryMode.value == DatePickerEntryMode.input ||
_entryMode.value == DatePickerEntryMode.inputOnly) {
final FormState form = _formKey.currentState!;
if (!form.validate()) {
setState(() => _autovalidateMode.value = AutovalidateMode.always);
return;
}
form.save();
}
Navigator.pop(context, _selectedDate.value);
}
void _handleCancel() {
Navigator.pop(context);
}
void _handleOnDatePickerModeChange() {
widget.onDatePickerModeChange?.call(_entryMode.value);
}
void _handleEntryModeToggle() {
setState(() {
switch (_entryMode.value) {
case DatePickerEntryMode.calendar:
_autovalidateMode.value = AutovalidateMode.disabled;
_entryMode.value = DatePickerEntryMode.input;
_handleOnDatePickerModeChange();
case DatePickerEntryMode.input:
_formKey.currentState!.save();
_entryMode.value = DatePickerEntryMode.calendar;
_handleOnDatePickerModeChange();
case DatePickerEntryMode.calendarOnly:
case DatePickerEntryMode.inputOnly:
assert(false, 'Can not change entry mode from ${_entryMode.value}');
}
});
}
void _handleDateChanged(DateTime date) {
setState(() => _selectedDate.value = date);
}
Size _dialogSize(BuildContext context) {
final bool useMaterial3 = Theme.of(context).useMaterial3;
final bool isCalendar = switch (_entryMode.value) {
DatePickerEntryMode.calendar || DatePickerEntryMode.calendarOnly => true,
DatePickerEntryMode.input || DatePickerEntryMode.inputOnly => false,
};
final Orientation orientation = MediaQuery.orientationOf(context);
return switch ((isCalendar, orientation)) {
(true, Orientation.portrait) when useMaterial3 => _calendarPortraitDialogSizeM3,
(false, Orientation.portrait) when useMaterial3 => _inputPortraitDialogSizeM3,
(true, Orientation.portrait) => _calendarPortraitDialogSizeM2,
(false, Orientation.portrait) => _inputPortraitDialogSizeM2,
(true, Orientation.landscape) => _calendarLandscapeDialogSize,
(false, Orientation.landscape) => _inputLandscapeDialogSize,
};
}
static const Map<ShortcutActivator, Intent> _formShortcutMap = <ShortcutActivator, Intent>{
// Pressing enter on the field will move focus to the next field or control.
SingleActivator(LogicalKeyboardKey.enter): NextFocusIntent(),
};
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final bool useMaterial3 = theme.useMaterial3;
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final Orientation orientation = MediaQuery.orientationOf(context);
final isLandscapeOrientation = orientation == Orientation.landscape;
final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context);
final DatePickerThemeData defaults = DatePickerTheme.defaults(context);
final TextTheme textTheme = theme.textTheme;
// There's no M3 spec for a landscape layout input (not calendar)
// date picker. To ensure that the date displayed in the input
// date picker's header fits in landscape mode, we override the M3
// default here.
TextStyle? headlineStyle;
if (useMaterial3) {
headlineStyle = datePickerTheme.headerHeadlineStyle ?? defaults.headerHeadlineStyle;
switch (_entryMode.value) {
case DatePickerEntryMode.input:
case DatePickerEntryMode.inputOnly:
if (orientation == Orientation.landscape) {
headlineStyle = textTheme.headlineSmall;
}
case DatePickerEntryMode.calendar:
case DatePickerEntryMode.calendarOnly:
// M3 default is OK.
}
} else {
headlineStyle = isLandscapeOrientation ? textTheme.headlineSmall : textTheme.headlineMedium;
}
final Color? headerForegroundColor =
datePickerTheme.headerForegroundColor ?? defaults.headerForegroundColor;
headlineStyle = headlineStyle?.copyWith(color: headerForegroundColor);
final Widget actions = ConstrainedBox(
constraints: const BoxConstraints(minHeight: 52.0),
child: MediaQuery.withClampedTextScaling(
maxScaleFactor: isLandscapeOrientation ? 1.6 : _kMaxTextScaleFactor,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: OverflowBar(
spacing: 8,
children: <Widget>[
TextButton(
style: datePickerTheme.cancelButtonStyle ?? defaults.cancelButtonStyle,
onPressed: _handleCancel,
child: Text(
widget.cancelText ??
(useMaterial3
? localizations.cancelButtonLabel
: localizations.cancelButtonLabel.toUpperCase()),
),
),
TextButton(
style: datePickerTheme.confirmButtonStyle ?? defaults.confirmButtonStyle,
onPressed: _handleOk,
child: Text(widget.confirmText ?? localizations.okButtonLabel),
),
],
),
),
),
),
);
CalendarDatePicker calendarDatePicker() {
return CalendarDatePicker(
calendarDelegate: widget.calendarDelegate,
key: _calendarPickerKey,
initialDate: _selectedDate.value,
firstDate: widget.firstDate,
lastDate: widget.lastDate,
currentDate: widget.currentDate,
onDateChanged: _handleDateChanged,
selectableDayPredicate: widget.selectableDayPredicate,
initialCalendarMode: widget.initialCalendarMode,
);
}
Form inputDatePicker() {
return Form(
key: _formKey,
autovalidateMode: _autovalidateMode.value,
child: SizedBox(
height: orientation == Orientation.portrait
? _inputFormPortraitHeight
: _inputFormLandscapeHeight,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Shortcuts(
shortcuts: _formShortcutMap,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Flexible(
child: MediaQuery.withClampedTextScaling(
maxScaleFactor: 2.0,
child: InputDatePickerFormField(
calendarDelegate: widget.calendarDelegate,
initialDate: _selectedDate.value,
firstDate: widget.firstDate,
lastDate: widget.lastDate,
onDateSubmitted: _handleDateChanged,
onDateSaved: _handleDateChanged,
selectableDayPredicate: widget.selectableDayPredicate,
errorFormatText: widget.errorFormatText,
errorInvalidText: widget.errorInvalidText,
fieldHintText: widget.fieldHintText,
fieldLabelText: widget.fieldLabelText,
keyboardType: widget.keyboardType,
autofocus: true,
),
),
),
],
),
),
),
),
);
}
final Widget picker;
final Widget? entryModeButton;
switch (_entryMode.value) {
case DatePickerEntryMode.calendar:
picker = calendarDatePicker();
entryModeButton = IconButton(
icon:
widget.switchToInputEntryModeIcon ??
Icon(useMaterial3 ? Icons.edit_outlined : Icons.edit),
color: headerForegroundColor,
tooltip: localizations.inputDateModeButtonLabel,
onPressed: _handleEntryModeToggle,
);
case DatePickerEntryMode.calendarOnly:
picker = calendarDatePicker();
entryModeButton = null;
case DatePickerEntryMode.input:
picker = inputDatePicker();
entryModeButton = IconButton(
icon: widget.switchToCalendarEntryModeIcon ?? const Icon(Icons.calendar_today),
color: headerForegroundColor,
tooltip: localizations.calendarModeButtonLabel,
onPressed: _handleEntryModeToggle,
);
case DatePickerEntryMode.inputOnly:
picker = inputDatePicker();
entryModeButton = null;
}
final Widget header = _DatePickerHeader(
helpText:
widget.helpText ??
(useMaterial3
? localizations.datePickerHelpText
: localizations.datePickerHelpText.toUpperCase()),
titleText: _selectedDate.value == null
? ''
: widget.calendarDelegate.formatMediumDate(_selectedDate.value!, localizations),
titleStyle: headlineStyle,
orientation: orientation,
isShort: orientation == Orientation.landscape,
entryModeButton: entryModeButton,
);
// Constrain the textScaleFactor to the largest supported value to prevent
// layout issues.
final double textScaleFactor =
MediaQuery.textScalerOf(context)
.clamp(maxScaleFactor: _kMaxTextScaleFactor)
.scale(_fontSizeToScale) /
_fontSizeToScale;
final Size dialogSize = _dialogSize(context) * textScaleFactor;
final DialogThemeData dialogTheme = theme.dialogTheme;
return Dialog(
backgroundColor: datePickerTheme.backgroundColor ?? defaults.backgroundColor,
elevation: useMaterial3
? datePickerTheme.elevation ?? defaults.elevation!
: datePickerTheme.elevation ?? dialogTheme.elevation ?? 24,
shadowColor: datePickerTheme.shadowColor ?? defaults.shadowColor,
surfaceTintColor: datePickerTheme.surfaceTintColor ?? defaults.surfaceTintColor,
shape: useMaterial3
? datePickerTheme.shape ?? defaults.shape
: datePickerTheme.shape ?? dialogTheme.shape ?? defaults.shape,
insetPadding: widget.insetPadding,
clipBehavior: Clip.antiAlias,
child: AnimatedContainer(
width: dialogSize.width,
height: dialogSize.height,
duration: _dialogSizeAnimationDuration,
curve: Curves.easeIn,
child: MediaQuery.withClampedTextScaling(
// Constrain the textScaleFactor to the largest supported value to prevent
// layout issues.
maxScaleFactor: _kMaxTextScaleFactor,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final Size portraitDialogSize = useMaterial3
? _inputPortraitDialogSizeM3
: _inputPortraitDialogSizeM2;
// Make sure the portrait dialog can fit the contents comfortably when
// resized from the landscape dialog.
final bool isFullyPortrait =
constraints.maxHeight >= math.min(dialogSize.height, portraitDialogSize.height);
switch (orientation) {
case Orientation.portrait:
final bool isInputMode =
_entryMode.value == DatePickerEntryMode.inputOnly ||
_entryMode.value == DatePickerEntryMode.input;
// When the portrait dialog does not fit vertically, hide the header when the entry mode
// is input, or hide the picker when the entry mode is not input.
final bool showHeader = isFullyPortrait || !isInputMode;
final bool showPicker = isFullyPortrait || isInputMode;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
if (showHeader) header,
if (useMaterial3) Divider(height: 0, color: datePickerTheme.dividerColor),
if (showPicker) ...<Widget>[Expanded(child: picker), actions],
],
);
case Orientation.landscape:
return Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
header,
if (useMaterial3)
VerticalDivider(width: 0, color: datePickerTheme.dividerColor),
Flexible(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(child: picker),
actions,
],
),
),
],
);
}
},
),
),
),
);
}
}
// A restorable [DatePickerEntryMode] value.
//
// This serializes each entry as a unique `int` value.
class _RestorableDatePickerEntryMode extends RestorableValue<DatePickerEntryMode> {
_RestorableDatePickerEntryMode(DatePickerEntryMode defaultValue) : _defaultValue = defaultValue;
final DatePickerEntryMode _defaultValue;
@override
DatePickerEntryMode createDefaultValue() => _defaultValue;
@override
void didUpdateValue(DatePickerEntryMode? oldValue) {
assert(debugIsSerializableForRestoration(value.index));
notifyListeners();
}
@override
DatePickerEntryMode fromPrimitives(Object? data) => DatePickerEntryMode.values[data! as int];
@override
Object? toPrimitives() => value.index;
}
// A restorable [AutovalidateMode] value.
//
// This serializes each entry as a unique `int` value.
class _RestorableAutovalidateMode extends RestorableValue<AutovalidateMode> {
_RestorableAutovalidateMode(AutovalidateMode defaultValue) : _defaultValue = defaultValue;
final AutovalidateMode _defaultValue;
@override
AutovalidateMode createDefaultValue() => _defaultValue;
@override
void didUpdateValue(AutovalidateMode? oldValue) {
assert(debugIsSerializableForRestoration(value.index));
notifyListeners();
}
@override
AutovalidateMode fromPrimitives(Object? data) => AutovalidateMode.values[data! as int];
@override
Object? toPrimitives() => value.index;
}
/// Re-usable widget that displays the selected date (in large font) and the
/// help text above it.
///
/// These types include:
///
/// * Single Date picker with calendar mode.
/// * Single Date picker with text input mode.
/// * Date Range picker with text input mode.
class _DatePickerHeader extends StatelessWidget {
/// Creates a header for use in a date picker dialog.
const _DatePickerHeader({
required this.helpText,
required this.titleText,
this.titleSemanticsLabel,
required this.titleStyle,
required this.orientation,
this.isShort = false,
this.entryModeButton,
});
static const double _datePickerHeaderLandscapeWidth = 152.0;
static const double _datePickerHeaderPortraitHeight = 120.0;
static const double _headerPaddingLandscape = 16.0;
/// The text that is displayed at the top of the header.
///
/// This is used to indicate to the user what they are selecting a date for.
final String helpText;
/// The text that is displayed at the center of the header.
final String titleText;
/// The semantic label associated with the [titleText].
final String? titleSemanticsLabel;
/// The [TextStyle] that the title text is displayed with.
final TextStyle? titleStyle;
/// The orientation is used to decide how to layout its children.
final Orientation orientation;
/// Indicates the header is being displayed in a shorter/narrower context.
///
/// This will be used to tighten up the space between the help text and date
/// text if `true`. Additionally, it will use a smaller typography style if
/// `true`.
///
/// This is necessary for displaying the manual input mode in
/// landscape orientation, in order to account for the keyboard height.
final bool isShort;
final Widget? entryModeButton;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context);
final DatePickerThemeData defaults = DatePickerTheme.defaults(context);
final Color? backgroundColor =
datePickerTheme.headerBackgroundColor ?? defaults.headerBackgroundColor;
final Color? foregroundColor =
datePickerTheme.headerForegroundColor ?? defaults.headerForegroundColor;
final TextStyle? helpStyle = (datePickerTheme.headerHelpStyle ?? defaults.headerHelpStyle)
?.copyWith(color: foregroundColor);
final double currentScale =
MediaQuery.textScalerOf(context).scale(_fontSizeToScale) / _fontSizeToScale;
final double maxHeaderTextScaleFactor = math.min(
currentScale,
entryModeButton != null ? _kMaxHeaderWithEntryTextScaleFactor : _kMaxHeaderTextScaleFactor,
);
final double textScaleFactor =
MediaQuery.textScalerOf(context)
.clamp(maxScaleFactor: maxHeaderTextScaleFactor)
.scale(_fontSizeToScale) /
_fontSizeToScale;
final double scaledFontSize = MediaQuery.textScalerOf(context)
.scale(titleStyle?.fontSize ?? 32);
final headerScaleFactor = textScaleFactor > 1 ? textScaleFactor : 1.0;
final help = Text(
helpText,
style: helpStyle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textScaler: MediaQuery.textScalerOf(context).clamp(
maxScaleFactor: math.min(
textScaleFactor,
orientation == Orientation.portrait
? _kMaxHelpPortraitTextScaleFactor
: _kMaxHelpLandscapeTextScaleFactor,
),
),
);
final title = Text(
titleText,
semanticsLabel: titleSemanticsLabel ?? titleText,
style: titleStyle,
maxLines: orientation == Orientation.portrait
? (scaledFontSize > 70 ? 2 : 1)
: scaledFontSize > 40
? 3
: 2,
overflow: TextOverflow.ellipsis,
textScaler: MediaQuery.textScalerOf(context).clamp(maxScaleFactor: textScaleFactor),
);
final double fontScaleAdjustedHeaderHeight = headerScaleFactor > 1.3
? headerScaleFactor - 0.2
: 1.0;
switch (orientation) {
case Orientation.portrait:
return Semantics(
container: true,
child: SizedBox(
height: _datePickerHeaderPortraitHeight * fontScaleAdjustedHeaderHeight,
child: Material(
color: backgroundColor,
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 24, end: 12, bottom: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(height: 16),
help,
const Flexible(child: SizedBox(height: 38)),
Row(
children: <Widget>[
Expanded(child: title),
if (entryModeButton != null)