Repository navigation
Expand file tree
/
Copy pathcheckbox.dart
More file actions
996 lines (906 loc) · 35.3 KB
/
Copy pathcheckbox.dart
File metadata and controls
996 lines (906 loc) · 35.3 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
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'checkbox_list_tile.dart';
/// @docImport 'list_tile.dart';
/// @docImport 'material.dart';
/// @docImport 'radio.dart';
/// @docImport 'slider.dart';
/// @docImport 'switch.dart';
library;
import 'package:cupertino_ui/cupertino_ui.dart';
import 'package:flutter/foundation.dart' show clampDouble;
import 'checkbox_theme.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'constants.dart';
import 'debug.dart';
import 'theme.dart';
import 'theme_data.dart';
part 'generated/checkbox_defaults_m3.g.dart';
// Examples can assume:
// bool _throwShotAway = false;
// late StateSetter setState;
enum _CheckboxType { material, adaptive }
/// A Material Design checkbox.
///
/// The checkbox itself does not maintain any state. Instead, when the state of
/// the checkbox changes, the widget calls the [onChanged] callback. Most
/// widgets that use a checkbox will listen for the [onChanged] callback and
/// rebuild the checkbox with a new [value] to update the visual appearance of
/// the checkbox.
///
/// The checkbox can optionally display three values - true, false, and null -
/// if [tristate] is true. When [value] is null a dash is displayed. By default
/// [tristate] is false and the checkbox's [value] must be true or false.
///
/// Requires one of its ancestors to be a [Material] widget.
///
/// <callout-box>
///
/// This example shows how you can override the default theme of
/// a [Checkbox] with a [WidgetStateProperty].
/// In this example, the checkbox's color will be `Colors.blue` when the [Checkbox]
/// is being pressed, hovered, or focused. Otherwise, the checkbox's color will
/// be `Colors.red`.
///
// TODO(framework): Replace the following block with a @dartpad directive
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
/// {@macro material_ui.dartpad_guide}
///
/// {@example /example/lib/checkbox/checkbox.0.dart#body}
///
/// </callout-box>
///
/// <callout-box>
///
/// This example shows what the checkbox error state looks like.
///
// TODO(framework): Replace the following block with a @dartpad directive
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
/// {@macro material_ui.dartpad_guide}
///
/// {@example /example/lib/checkbox/checkbox.1.dart#body}
///
/// </callout-box>
///
/// See also:
///
/// * [CheckboxListTile], which combines this widget with a [ListTile] so that
/// you can give the checkbox a label.
/// * [Switch], a widget with semantics similar to [Checkbox].
/// * [Radio], for selecting among a set of explicit values.
/// * [Slider], for selecting a value in a range.
/// * <https://material.io/design/components/selection-controls.html#checkboxes>
/// * <https://material.io/design/components/lists.html#types>
class Checkbox extends StatefulWidget {
/// Creates a Material Design checkbox.
///
/// The checkbox itself does not maintain any state. Instead, when the state of
/// the checkbox changes, the widget calls the [onChanged] callback. Most
/// widgets that use a checkbox will listen for the [onChanged] callback and
/// rebuild the checkbox with a new [value] to update the visual appearance of
/// the checkbox.
///
/// The following arguments are required:
///
/// * [value], which determines whether the checkbox is checked. The [value]
/// can only be null if [tristate] is true.
/// * [onChanged], which is called when the value of the checkbox should
/// change. It can be set to null to disable the checkbox.
const Checkbox({
super.key,
required this.value,
this.tristate = false,
required this.onChanged,
this.mouseCursor,
this.activeColor,
this.fillColor,
this.checkColor,
this.focusColor,
this.hoverColor,
this.overlayColor,
this.splashRadius,
this.materialTapTargetSize,
this.visualDensity,
this.focusNode,
this.autofocus = false,
this.shape,
this.side,
this.isError = false,
this.semanticLabel,
this.markInsets,
}) : _checkboxType = _CheckboxType.material,
assert(tristate || value != null);
/// Creates an adaptive [Checkbox] based on whether the target platform is iOS
/// or macOS, following Material design's
/// [Cross-platform guidelines](https://material.io/design/platform-guidance/cross-platform-adaptation.html).
///
/// On iOS and macOS, this constructor creates a [CupertinoCheckbox], which has
/// matching functionality and presentation as Material checkboxes, and are the
/// graphics expected on iOS. On other platforms, this creates a Material
/// design [Checkbox].
///
/// If a [CupertinoCheckbox] is created, the following parameters are ignored:
/// [fillColor], [hoverColor], [overlayColor], [splashRadius],
/// [materialTapTargetSize], [visualDensity], [isError], [markInsets]. However,
/// [shape] and [side] will still affect the [CupertinoCheckbox] and should be
/// handled if native fidelity is important.
///
/// The target platform is based on the current [Theme]: [ThemeData.platform].
const Checkbox.adaptive({
super.key,
required this.value,
this.tristate = false,
required this.onChanged,
this.mouseCursor,
this.activeColor,
this.fillColor,
this.checkColor,
this.focusColor,
this.hoverColor,
this.overlayColor,
this.splashRadius,
this.materialTapTargetSize,
this.visualDensity,
this.focusNode,
this.autofocus = false,
this.shape,
this.side,
this.isError = false,
this.semanticLabel,
this.markInsets,
}) : _checkboxType = _CheckboxType.adaptive,
assert(tristate || value != null);
/// Whether this checkbox is checked.
///
/// When [tristate] is true, a value of null corresponds to the mixed state.
/// When [tristate] is false, this value must not be null.
final bool? value;
/// Called when the value of the checkbox should change.
///
/// The checkbox passes the new value to the callback but does not actually
/// change state until the parent widget rebuilds the checkbox with the new
/// value.
///
/// If this callback is null, the checkbox will be displayed as disabled
/// and will not respond to input gestures.
///
/// When the checkbox is tapped, if [tristate] is false (the default) then
/// the [onChanged] callback will be applied to `!value`. If [tristate] is
/// true this callback cycle from false to true to null.
///
/// The callback provided to [onChanged] should update the state of the parent
/// [StatefulWidget] using the [State.setState] method, so that the parent
/// gets rebuilt; for example:
///
/// ```dart
/// Checkbox(
/// value: _throwShotAway,
/// onChanged: (bool? newValue) {
/// setState(() {
/// _throwShotAway = newValue!;
/// });
/// },
/// )
/// ```
final ValueChanged<bool?>? onChanged;
/// {@template material_ui.checkbox.mouseCursor}
/// The cursor for a mouse pointer when it enters or is hovering over the
/// widget.
///
/// If [mouseCursor] is a [WidgetStateMouseCursor],
/// [WidgetStateProperty.resolve] is used for the following [WidgetState]s:
///
/// * [WidgetState.selected].
/// * [WidgetState.focused].
/// * [WidgetState.disabled].
/// {@endtemplate}
///
/// When [value] is null and [tristate] is true, [WidgetState.selected] is
/// included as a state.
///
/// If this property is null, the value of [CheckboxThemeData.mouseCursor] is used.
/// If that is also null, [WidgetStateMouseCursor.adaptiveClickable] is used.
final MouseCursor? mouseCursor;
/// The color to use when this checkbox is checked.
///
/// Defaults to [ColorScheme.secondary].
///
/// If [fillColor] returns a non-null color in the [WidgetState.selected]
/// state, it will be used instead of this color.
final Color? activeColor;
/// {@template material_ui.checkbox.fillColor}
/// The color that fills the checkbox, in all [WidgetState]s.
///
/// Resolves in the following states:
/// * [WidgetState.selected].
/// * [WidgetState.hovered].
/// * [WidgetState.focused].
/// * [WidgetState.disabled].
///
/// <callout-box>
///
/// This example resolves the [fillColor] based on the current [WidgetState]
/// of the [Checkbox], providing a different [Color] when it is
/// [WidgetState.disabled].
///
/// {@example /example/lib/checkbox/checkbox.snippet.0.dart#body indent=strip}
///
/// </callout-box>
/// {@endtemplate}
///
/// If null, then the value of [activeColor] is used in the selected
/// state. If that is also null, the value of [CheckboxThemeData.fillColor]
/// is used. If that is also null, then [ThemeData.disabledColor] is used in
/// the disabled state, [ColorScheme.secondary] is used in the
/// selected state, and [ThemeData.unselectedWidgetColor] is used in the
/// default state.
final WidgetStateProperty<Color?>? fillColor;
/// {@template material_ui.checkbox.checkColor}
/// The color to use for the check icon when this checkbox is checked.
/// {@endtemplate}
///
/// If null, then the value of [CheckboxThemeData.checkColor] is used. If
/// that is also null, then Color(0xFFFFFFFF) is used.
final Color? checkColor;
/// If true the checkbox's [value] can be true, false, or null.
///
/// [Checkbox] displays a dash when its value is null.
///
/// When a tri-state checkbox ([tristate] is true) is tapped, its [onChanged]
/// callback will be applied to true if the current value is false, to null if
/// value is true, and to false if value is null (i.e. it cycles through false
/// => true => null => false when tapped).
///
/// If tristate is false (the default), [value] must not be null.
final bool tristate;
/// {@template material_ui.checkbox.materialTapTargetSize}
/// Configures the minimum size of the tap target.
/// {@endtemplate}
///
/// If null, then the value of [CheckboxThemeData.materialTapTargetSize] is
/// used. If that is also null, then the value of
/// [ThemeData.materialTapTargetSize] is used.
///
/// See also:
///
/// * [MaterialTapTargetSize], for a description of how this affects tap targets.
final MaterialTapTargetSize? materialTapTargetSize;
/// {@template material_ui.checkbox.visualDensity}
/// Defines how compact the checkbox's layout will be.
/// {@endtemplate}
///
/// {@macro material_ui.themedata.visualDensity}
///
/// If null, then the value of [CheckboxThemeData.visualDensity] is used. If
/// that is also null and if [ThemeData.useMaterial3] is false, then the
/// value of [ThemeData.visualDensity] is used. Otherwise, the default value
/// is [VisualDensity.standard].
///
/// See also:
///
/// * [ThemeData.visualDensity], which specifies the [visualDensity] for all
/// widgets within a [Theme].
final VisualDensity? visualDensity;
/// The color for the checkbox's [Material] when it has the input focus.
///
/// If [overlayColor] returns a non-null color in the [WidgetState.focused]
/// state, it will be used instead.
///
/// If null, then the value of [CheckboxThemeData.overlayColor] is used in the
/// focused state. If that is also null, then the value of
/// [ThemeData.focusColor] is used.
final Color? focusColor;
/// {@template material_ui.checkbox.hoverColor}
/// The color for the checkbox's [Material] when a pointer is hovering over it.
///
/// If [overlayColor] returns a non-null color in the [WidgetState.hovered]
/// state, it will be used instead.
/// {@endtemplate}
///
/// If null, then the value of [CheckboxThemeData.overlayColor] is used in the
/// hovered state. If that is also null, then the value of
/// [ThemeData.hoverColor] is used.
final Color? hoverColor;
/// {@template material_ui.checkbox.overlayColor}
/// The color for the checkbox's [Material].
///
/// Resolves in the following states:
/// * [WidgetState.pressed].
/// * [WidgetState.selected].
/// * [WidgetState.hovered].
/// * [WidgetState.focused].
/// {@endtemplate}
///
/// If null, then the value of [activeColor] with alpha
/// [kRadialReactionAlpha], [focusColor] and [hoverColor] is used in the
/// pressed, focused and hovered state. If that is also null,
/// the value of [CheckboxThemeData.overlayColor] is used. If that is
/// also null, then the value of [ColorScheme.secondary] with alpha
/// [kRadialReactionAlpha], [ThemeData.focusColor] and [ThemeData.hoverColor]
/// is used in the pressed, focused and hovered state.
final WidgetStateProperty<Color?>? overlayColor;
/// {@template material_ui.checkbox.splashRadius}
/// The splash radius of the circular [Material] ink response.
/// {@endtemplate}
///
/// If null, then the value of [CheckboxThemeData.splashRadius] is used. If
/// that is also null, then [kRadialReactionRadius] is used.
final double? splashRadius;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// {@macro flutter.widgets.Focus.autofocus}
final bool autofocus;
/// {@template material_ui.checkbox.shape}
/// The shape of the checkbox's [Material].
/// {@endtemplate}
///
/// If this property is null then the ambient [CheckboxThemeData.shape]
/// is used. If that's null then the shape will be a [RoundedRectangleBorder]
/// with a circular corner radius of 1.0 in Material 2, and 2.0 in Material 3.
final OutlinedBorder? shape;
/// {@template material_ui.checkbox.side}
/// The color and width of the checkbox's border.
///
/// This property can be a [WidgetStateBorderSide] that can
/// specify different border color and widths depending on the
/// checkbox's state.
///
/// Resolves in the following states:
/// * [WidgetState.pressed].
/// * [WidgetState.selected].
/// * [WidgetState.hovered].
/// * [WidgetState.focused].
/// * [WidgetState.disabled].
/// * [WidgetState.error].
///
/// If this property is not a [WidgetStateBorderSide] and it is
/// non-null, then it is only rendered when the checkbox's value is
/// false. The difference in interpretation is for backwards
/// compatibility.
/// {@endtemplate}
///
/// If this property is null, then the ambient [CheckboxThemeData.side] is
/// used. If that is also null, then the side will be width 2.
final BorderSide? side;
/// {@template material_ui.checkbox.isError}
/// True if this checkbox wants to show an error state.
///
/// The checkbox will have different default container color and check color when
/// this is true. This is only used when [ThemeData.useMaterial3] is set to true.
/// {@endtemplate}
///
/// Defaults to false.
final bool isError;
/// {@template material_ui.checkbox.semanticLabel}
/// The semantic label for the checkbox that will be announced by screen readers.
///
/// This is announced by assistive technologies (e.g TalkBack/VoiceOver).
///
/// This label does not show in the UI.
/// {@endtemplate}
final String? semanticLabel;
/// {@template material_ui.checkbox.markInsets}
/// The insets applied around the check mark when the checkbox is checked or
/// in its indeterminate (tristate) state.
///
/// This insets the check mark inward; the size of the checkbox box itself
/// is not affected. The check mark and its stroke shrink to fit the
/// remaining space, so the mark stays proportional. Its size is the smaller
/// of the remaining width and height, and it is centered in the remaining
/// space, so an inset on one axis also shrinks it on the other. For example,
/// `EdgeInsets.only(left: 9.0)` draws a half-size mark centered in the right
/// half of the box.
///
/// On iOS and macOS, when using [Checkbox.adaptive], this property has no
/// effect, because the checkbox delegates to [CupertinoCheckbox], which does
/// not support insets.
///
/// Must be non-negative. If the horizontal or vertical insets are
/// greater than or equal to the checkbox size, the check mark or indeterminate
/// dash is not painted.
///
/// If null, [CheckboxThemeData.markInsets] is used. If that is also null,
/// it defaults to [EdgeInsets.zero] and the check mark renders at full size.
/// {@endtemplate}
final EdgeInsets? markInsets;
/// The width of a checkbox widget.
static const double width = 18.0;
final _CheckboxType _checkboxType;
@override
State<Checkbox> createState() => _CheckboxState();
}
class _CheckboxState extends State<Checkbox> with TickerProviderStateMixin, ToggleableStateMixin {
final _CheckboxPainter _painter = _CheckboxPainter();
bool? _previousValue;
@override
void initState() {
super.initState();
_previousValue = widget.value;
}
@override
void didUpdateWidget(Checkbox oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.value != widget.value) {
_previousValue = oldWidget.value;
animateToValue();
}
}
@override
void dispose() {
_painter.dispose();
super.dispose();
}
@override
ValueChanged<bool?>? get onChanged => widget.onChanged;
@override
bool get tristate => widget.tristate;
@override
bool? get value => widget.value;
@override
Duration? get reactionAnimationDuration => kRadialReactionDuration;
WidgetStateProperty<Color?> get _widgetFillColor {
return WidgetStateProperty.resolveWith((Set<WidgetState> states) {
if (states.contains(WidgetState.disabled)) {
return null;
}
if (states.contains(WidgetState.selected)) {
return widget.activeColor;
}
return null;
});
}
BorderSide? _resolveSide(BorderSide? side, Set<WidgetState> states) {
if (side is WidgetStateBorderSide) {
return WidgetStateProperty.resolveAs<BorderSide?>(side, states);
}
if (!states.contains(WidgetState.selected)) {
return side;
}
return null;
}
@override
Widget build(BuildContext context) {
switch (widget._checkboxType) {
case _CheckboxType.material:
break;
case _CheckboxType.adaptive:
final ThemeData theme = Theme.of(context);
switch (theme.platform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
break;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return CupertinoCheckbox(
value: value,
tristate: tristate,
onChanged: onChanged,
mouseCursor: widget.mouseCursor,
activeColor: widget.activeColor,
checkColor: widget.checkColor,
focusColor: widget.focusColor,
focusNode: widget.focusNode,
autofocus: widget.autofocus,
side: widget.side,
shape: widget.shape,
semanticLabel: widget.semanticLabel,
);
}
}
assert(debugCheckHasMaterial(context));
final CheckboxThemeData checkboxTheme = CheckboxTheme.of(context);
final CheckboxThemeData defaults = Theme.of(context).useMaterial3
? _CheckboxDefaultsM3(context)
: _CheckboxDefaultsM2(context);
final MaterialTapTargetSize effectiveMaterialTapTargetSize =
widget.materialTapTargetSize ??
checkboxTheme.materialTapTargetSize ??
defaults.materialTapTargetSize!;
final VisualDensity effectiveVisualDensity =
widget.visualDensity ?? checkboxTheme.visualDensity ?? defaults.visualDensity!;
Size size = switch (effectiveMaterialTapTargetSize) {
MaterialTapTargetSize.padded => const Size(
kMinInteractiveDimension,
kMinInteractiveDimension,
),
MaterialTapTargetSize.shrinkWrap => const Size(
kMinInteractiveDimension - 8.0,
kMinInteractiveDimension - 8.0,
),
};
size += effectiveVisualDensity.baseSizeAdjustment;
final WidgetStateProperty<MouseCursor> effectiveMouseCursor =
WidgetStateProperty.resolveWith<MouseCursor>((Set<WidgetState> states) {
return WidgetStateProperty.resolveAs<MouseCursor?>(widget.mouseCursor, states) ??
checkboxTheme.mouseCursor?.resolve(states) ??
WidgetStateMouseCursor.adaptiveClickable.resolve(states);
});
// Colors need to be resolved in selected and non selected states separately
final Set<WidgetState> activeStates = states..add(WidgetState.selected);
final Set<WidgetState> inactiveStates = states..remove(WidgetState.selected);
if (widget.isError) {
activeStates.add(WidgetState.error);
inactiveStates.add(WidgetState.error);
}
final Color? activeColor =
widget.fillColor?.resolve(activeStates) ??
_widgetFillColor.resolve(activeStates) ??
checkboxTheme.fillColor?.resolve(activeStates);
final Color effectiveActiveColor = activeColor ?? defaults.fillColor!.resolve(activeStates)!;
final Color? inactiveColor =
widget.fillColor?.resolve(inactiveStates) ??
_widgetFillColor.resolve(inactiveStates) ??
checkboxTheme.fillColor?.resolve(inactiveStates);
final Color effectiveInactiveColor =
inactiveColor ?? defaults.fillColor!.resolve(inactiveStates)!;
final BorderSide activeSide =
_resolveSide(widget.side, activeStates) ??
_resolveSide(checkboxTheme.side, activeStates) ??
_resolveSide(defaults.side, activeStates)!;
final BorderSide inactiveSide =
_resolveSide(widget.side, inactiveStates) ??
_resolveSide(checkboxTheme.side, inactiveStates) ??
_resolveSide(defaults.side, inactiveStates)!;
final Set<WidgetState> focusedStates = states..add(WidgetState.focused);
if (widget.isError) {
focusedStates.add(WidgetState.error);
}
Color effectiveFocusOverlayColor =
widget.overlayColor?.resolve(focusedStates) ??
widget.focusColor ??
checkboxTheme.overlayColor?.resolve(focusedStates) ??
defaults.overlayColor!.resolve(focusedStates)!;
final Set<WidgetState> hoveredStates = states..add(WidgetState.hovered);
if (widget.isError) {
hoveredStates.add(WidgetState.error);
}
Color effectiveHoverOverlayColor =
widget.overlayColor?.resolve(hoveredStates) ??
widget.hoverColor ??
checkboxTheme.overlayColor?.resolve(hoveredStates) ??
defaults.overlayColor!.resolve(hoveredStates)!;
final activePressedStates = activeStates..add(WidgetState.pressed);
final Color effectiveActivePressedOverlayColor =
widget.overlayColor?.resolve(activePressedStates) ??
checkboxTheme.overlayColor?.resolve(activePressedStates) ??
activeColor?.withAlpha(kRadialReactionAlpha) ??
defaults.overlayColor!.resolve(activePressedStates)!;
final inactivePressedStates = inactiveStates..add(WidgetState.pressed);
final Color effectiveInactivePressedOverlayColor =
widget.overlayColor?.resolve(inactivePressedStates) ??
checkboxTheme.overlayColor?.resolve(inactivePressedStates) ??
inactiveColor?.withAlpha(kRadialReactionAlpha) ??
defaults.overlayColor!.resolve(inactivePressedStates)!;
if (downPosition != null) {
effectiveHoverOverlayColor = states.contains(WidgetState.selected)
? effectiveActivePressedOverlayColor
: effectiveInactivePressedOverlayColor;
effectiveFocusOverlayColor = states.contains(WidgetState.selected)
? effectiveActivePressedOverlayColor
: effectiveInactivePressedOverlayColor;
}
final Set<WidgetState> checkStates = widget.isError ? (states..add(WidgetState.error)) : states;
final Color effectiveCheckColor =
widget.checkColor ??
checkboxTheme.checkColor?.resolve(checkStates) ??
defaults.checkColor!.resolve(checkStates)!;
final double effectiveSplashRadius =
widget.splashRadius ?? checkboxTheme.splashRadius ?? defaults.splashRadius!;
final EdgeInsets markInsets = widget.markInsets ?? checkboxTheme.markInsets ?? EdgeInsets.zero;
return Semantics(
label: widget.semanticLabel,
checked: widget.value ?? false,
mixed: widget.tristate ? widget.value == null : null,
child: buildToggleable(
mouseCursor: effectiveMouseCursor,
focusNode: widget.focusNode,
autofocus: widget.autofocus,
size: size,
painter: _painter
..position = position
..reaction = reaction
..reactionFocusFade = reactionFocusFade
..reactionHoverFade = reactionHoverFade
..inactiveReactionColor = effectiveInactivePressedOverlayColor
..reactionColor = effectiveActivePressedOverlayColor
..hoverColor = effectiveHoverOverlayColor
..focusColor = effectiveFocusOverlayColor
..splashRadius = effectiveSplashRadius
..downPosition = downPosition
..isFocused = states.contains(WidgetState.focused)
..isHovered = states.contains(WidgetState.hovered)
..activeColor = effectiveActiveColor
..inactiveColor = effectiveInactiveColor
..checkColor = effectiveCheckColor
..value = value
..previousValue = _previousValue
..shape = widget.shape ?? checkboxTheme.shape ?? defaults.shape!
..activeSide = activeSide
..markInsets = markInsets
..inactiveSide = inactiveSide,
),
);
}
}
const double _kEdgeSize = Checkbox.width;
const double _kStrokeWidth = 2.0;
class _CheckboxPainter extends ToggleablePainter {
Color get checkColor => _checkColor!;
Color? _checkColor;
set checkColor(Color value) {
if (_checkColor == value) {
return;
}
_checkColor = value;
notifyListeners();
}
bool? get value => _value;
bool? _value;
set value(bool? value) {
if (_value == value) {
return;
}
_value = value;
notifyListeners();
}
bool? get previousValue => _previousValue;
bool? _previousValue;
set previousValue(bool? value) {
if (_previousValue == value) {
return;
}
_previousValue = value;
notifyListeners();
}
OutlinedBorder get shape => _shape!;
OutlinedBorder? _shape;
set shape(OutlinedBorder value) {
if (_shape == value) {
return;
}
_shape = value;
notifyListeners();
}
EdgeInsets get markInsets => _markInsets;
EdgeInsets _markInsets = EdgeInsets.zero;
set markInsets(EdgeInsets value) {
assert(value.isNonNegative, 'markInsets must be non-negative.');
if (_markInsets == value) {
return;
}
_markInsets = value;
notifyListeners(); // triggers repaint when it changes
}
BorderSide get activeSide => _activeSide!;
BorderSide? _activeSide;
set activeSide(BorderSide value) {
if (_activeSide == value) {
return;
}
_activeSide = value;
notifyListeners();
}
BorderSide get inactiveSide => _inactiveSide!;
BorderSide? _inactiveSide;
set inactiveSide(BorderSide value) {
if (_inactiveSide == value) {
return;
}
_inactiveSide = value;
notifyListeners();
}
// The square outer bounds of the checkbox at t, with the specified origin.
// At t == 0.0, the outer rect's size is _kEdgeSize (Checkbox.width)
// At t == 0.5, .. is _kEdgeSize - _kStrokeWidth
// At t == 1.0, .. is _kEdgeSize
Rect _outerRectAt(Offset origin, double t) {
final double inset = 1.0 - (t - 0.5).abs() * 2.0;
final double size = _kEdgeSize - inset * _kStrokeWidth;
final rect = Rect.fromLTWH(origin.dx + inset, origin.dy + inset, size, size);
return rect;
}
// The checkbox's fill color
Color _colorAt(double t) {
// As t goes from 0.0 to 0.25, animate from the inactiveColor to activeColor.
return t >= 0.25 ? activeColor : Color.lerp(inactiveColor, activeColor, t * 4.0)!;
}
// White stroke used to paint the check and dash.
Paint _createStrokePaint() {
return Paint()
..color = checkColor
..style = PaintingStyle.stroke
..strokeWidth = _kStrokeWidth;
}
// The square that the check mark or the indeterminate dash is drawn in.
//
// The square is inset by [markInsets] and then scaled down uniformly to fit
// whatever space is left, so that the mark keeps its aspect ratio no matter
// how asymmetric the insets are. It is centered in the space the insets leave
// behind. Returns null when the insets leave no room to draw in.
Rect? _markSquare() {
final double innerWidth = clampDouble(_kEdgeSize - _markInsets.horizontal, 0.0, _kEdgeSize);
final double innerHeight = clampDouble(_kEdgeSize - _markInsets.vertical, 0.0, _kEdgeSize);
if (innerWidth <= 0.0 || innerHeight <= 0.0) {
return null;
}
final side = innerWidth < innerHeight ? innerWidth : innerHeight;
return Rect.fromLTWH(
_markInsets.left + (innerWidth - side) / 2.0,
_markInsets.top + (innerHeight - side) / 2.0,
side,
side,
);
}
void _drawBox(Canvas canvas, Rect outer, Paint paint, BorderSide? side) {
if (shape.preferPaintInterior) {
shape.paintInterior(canvas, outer, paint);
} else {
canvas.drawPath(shape.getOuterPath(outer), paint);
}
if (side != null) {
shape.copyWith(side: side).paint(canvas, outer);
}
}
void _drawCheck(Canvas canvas, Offset origin, double t, Paint paint) {
assert(t >= 0.0 && t <= 1.0);
// As t goes from 0.0 to 1.0, animate the two check mark strokes from the
// short side to the long side.
final Rect? square = _markSquare();
if (square == null) {
return;
}
// Shrink the stroke by the same factor so a smaller mark doesn't look chunky.
paint.strokeWidth = _kStrokeWidth * (square.width / _kEdgeSize);
final path = Path();
final start = Offset(square.left + square.width * 0.15, square.top + square.height * 0.45);
final mid = Offset(square.left + square.width * 0.4, square.top + square.height * 0.7);
final end = Offset(square.left + square.width * 0.85, square.top + square.height * 0.25);
if (t < 0.5) {
final double strokeT = t * 2.0;
final Offset drawMid = Offset.lerp(start, mid, strokeT)!;
path.moveTo(origin.dx + start.dx, origin.dy + start.dy);
path.lineTo(origin.dx + drawMid.dx, origin.dy + drawMid.dy);
} else {
final double strokeT = (t - 0.5) * 2.0;
final Offset drawEnd = Offset.lerp(mid, end, strokeT)!;
path.moveTo(origin.dx + start.dx, origin.dy + start.dy);
path.lineTo(origin.dx + mid.dx, origin.dy + mid.dy);
path.lineTo(origin.dx + drawEnd.dx, origin.dy + drawEnd.dy);
}
canvas.drawPath(path, paint);
}
void _drawDash(Canvas canvas, Offset origin, double t, Paint paint) {
assert(t >= 0.0 && t <= 1.0);
// As t goes from 0.0 to 1.0, animate the horizontal line from the
// mid point outwards.
final Rect? square = _markSquare();
if (square == null) {
return;
}
paint.strokeWidth = _kStrokeWidth * (square.width / _kEdgeSize);
final start = Offset(square.left + square.width * 0.2, square.top + square.height * 0.5);
final mid = Offset(square.left + square.width * 0.5, square.top + square.height * 0.5);
final end = Offset(square.left + square.width * 0.8, square.top + square.height * 0.5);
final Offset drawStart = Offset.lerp(start, mid, 1.0 - t)!;
final Offset drawEnd = Offset.lerp(mid, end, t)!;
canvas.drawLine(origin + drawStart, origin + drawEnd, paint);
}
@override
void paint(Canvas canvas, Size size) {
paintRadialReaction(canvas: canvas, origin: size.center(Offset.zero));
final Paint strokePaint = _createStrokePaint();
final origin = size / 2.0 - const Size.square(_kEdgeSize) / 2.0 as Offset;
final double tNormalized = switch (position.status) {
AnimationStatus.forward || AnimationStatus.completed => position.value,
AnimationStatus.reverse || AnimationStatus.dismissed => 1.0 - position.value,
};
// Four cases: false to null, false to true, null to false, true to false
if (previousValue == false || value == false) {
final double t = value == false ? 1.0 - tNormalized : tNormalized;
final Rect outer = _outerRectAt(origin, t);
final paint = Paint()..color = _colorAt(t);
if (t <= 0.5) {
final BorderSide border = BorderSide.lerp(inactiveSide, activeSide, t);
_drawBox(canvas, outer, paint, border);
} else {
_drawBox(canvas, outer, paint, activeSide);
final double tShrink = (t - 0.5) * 2.0;
if (previousValue == null || value == null) {
_drawDash(canvas, origin, tShrink, strokePaint);
} else {
_drawCheck(canvas, origin, tShrink, strokePaint);
}
}
} else {
// Two cases: null to true, true to null
final Rect outer = _outerRectAt(origin, 1.0);
final paint = Paint()..color = _colorAt(1.0);
_drawBox(canvas, outer, paint, activeSide);
if (tNormalized <= 0.5) {
final double tShrink = 1.0 - tNormalized * 2.0;
if (previousValue ?? false) {
_drawCheck(canvas, origin, tShrink, strokePaint);
} else {
_drawDash(canvas, origin, tShrink, strokePaint);
}
} else {
final double tExpand = (tNormalized - 0.5) * 2.0;
if (value ?? false) {
_drawCheck(canvas, origin, tExpand, strokePaint);
} else {
_drawDash(canvas, origin, tExpand, strokePaint);
}
}
}
}
}
// Hand coded defaults based on Material Design 2.
class _CheckboxDefaultsM2 extends CheckboxThemeData {
_CheckboxDefaultsM2(BuildContext context)
: _theme = Theme.of(context),
_colors = Theme.of(context).colorScheme;
final ThemeData _theme;
final ColorScheme _colors;
@override
WidgetStateBorderSide? get side {
return WidgetStateBorderSide.resolveWith((Set<WidgetState> states) {
if (states.contains(WidgetState.disabled)) {
if (states.contains(WidgetState.selected)) {
return const BorderSide(width: 2.0, color: Colors.transparent);
}
return BorderSide(width: 2.0, color: _theme.disabledColor);
}
if (states.contains(WidgetState.selected)) {
return const BorderSide(width: 2.0, color: Colors.transparent);
}
return BorderSide(width: 2.0, color: _theme.unselectedWidgetColor);
});
}
@override
WidgetStateProperty<Color> get fillColor {
return WidgetStateProperty.resolveWith((Set<WidgetState> states) {
if (states.contains(WidgetState.disabled)) {
if (states.contains(WidgetState.selected)) {
return _theme.disabledColor;
}
return Colors.transparent;
}
if (states.contains(WidgetState.selected)) {
return _colors.secondary;
}
return Colors.transparent;
});
}
@override
WidgetStateProperty<Color> get checkColor {
return WidgetStateProperty.all<Color>(const Color(0xFFFFFFFF));
}
@override
WidgetStateProperty<Color?> get overlayColor {
return WidgetStateProperty.resolveWith((Set<WidgetState> states) {
if (states.contains(WidgetState.pressed)) {
return fillColor.resolve(states).withAlpha(kRadialReactionAlpha);
}
if (states.contains(WidgetState.hovered)) {
return _theme.hoverColor;
}
if (states.contains(WidgetState.focused)) {
return _theme.focusColor;
}
return Colors.transparent;
});
}
@override
double get splashRadius => kRadialReactionRadius;
@override
MaterialTapTargetSize get materialTapTargetSize => _theme.materialTapTargetSize;
@override
VisualDensity get visualDensity => _theme.visualDensity;
@override
OutlinedBorder get shape =>
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(1.0)));
}