Repository navigation
Expand file tree
/
Copy pathswitch.dart
More file actions
1445 lines (1290 loc) · 47.4 KB
/
Copy pathswitch.dart
File metadata and controls
1445 lines (1290 loc) · 47.4 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 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Examples can assume:
// bool _giveVerse = false;
// bool _lights = false;
// void setState(VoidCallback fn) { }
// TODO(QuncCccccc): Remove ignore once https://github.com/flutter/flutter/issues/196406 is fixed.
// ignore: uri_does_not_exist_in_doc_import
/// @docImport 'package:material_ui/material_ui.dart';
///
/// @docImport 'list_tile.dart';
library;
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'colors.dart';
import 'constants.dart';
import 'theme.dart';
// Hand coded defaults eyeballed from an iOS simulator running iOS version 17.5.
const double _kDisabledOpacity = 0.5;
const double _kThumbRadius = 14.0;
const double _kTrackHeight = 31.0;
const double _kTrackWidth = 51.0;
const Size _kSwitchSize = Size(59.0, 39.0);
const double _kThumbExtensionFactor = 7.0;
const List<BoxShadow> _kSwitchBoxShadows = <BoxShadow>[
BoxShadow(color: Color(0x26000000), offset: Offset(0, 3), blurRadius: 8.0),
BoxShadow(color: Color(0x0F000000), offset: Offset(0, 3), blurRadius: 1.0),
];
// The drag distance (as a fraction of the track width) beyond which the switch
// must be dragged to commit the state change.
// This threshold is used when the user is dragging to a new state.
const double _kDragCommitThreshold = 0.7;
// The drag distance (as a fraction of the track width) past which the user must
// drag back to reverse a state change that has already been visually committed
// during the drag.
// This threshold is used when the user is dragging back to the original state.
const double _kDragReverseThreshold = 0.2;
// Label sizes and padding taken from xcode inspector.
// See https://github.com/flutter/flutter/issues/4830#issuecomment-528495360.
const double _kOnLabelWidth = 1.0;
const double _kOnLabelHeight = 10.0;
const double _kOnLabelPaddingHorizontal = 11.0;
const double _kOffLabelWidth = 1.0;
const double _kOffLabelPaddingHorizontal = 12.0;
const double _kOffLabelRadius = 5.0;
const CupertinoDynamicColor _kOffLabelColor = CupertinoDynamicColor.withBrightnessAndContrast(
debugLabel: 'offSwitchLabel',
// Source: https://github.com/flutter/flutter/pull/39993#discussion_r321946033
color: Color.fromARGB(255, 179, 179, 179),
// Source: https://github.com/flutter/flutter/pull/39993#issuecomment-535196665
darkColor: Color.fromARGB(255, 179, 179, 179),
// Source: https://github.com/flutter/flutter/pull/127776#discussion_r1244208264
highContrastColor: Color.fromARGB(255, 255, 255, 255),
darkHighContrastColor: Color.fromARGB(255, 255, 255, 255),
);
/// An iOS-style switch.
///
/// Used to toggle the on/off state of a single setting.
///
/// Learn more about [CupertinoSwitch] on the [Flutter YouTube channel](https://www.youtube.com/watch?v=24tg_N4sdMQ).
///
/// The switch itself does not maintain its toggle state. Instead, when the
/// toggle state of the switch changes, the widget calls the [onChanged]
/// callback. Most widgets that use a switch will listen for the [onChanged]
/// callback and rebuild the switch with a new [value] to update the visual
/// appearance of the switch.
///
/// <callout-box>
///
/// This example shows a toggleable [CupertinoSwitch]. When the thumb slides to
/// the other side of the track, the switch is toggled between on/off.
///
// TODO(framework): Replace the following block with a @dartpad directive
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
/// {@macro cupertino_ui.dartpad_guide}
///
/// {@example /example/lib/switch/cupertino_switch.0.dart#body}
///
/// </callout-box>
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
///
/// This sample shows how to use a [CupertinoSwitch] in a [CupertinoListTile]. The
/// [MergeSemantics] is used to turn the entire [CupertinoListTile] into a single item
/// for accessibility tools.
///
/// ```dart
/// MergeSemantics(
/// child: CupertinoListTile(
/// title: const Text('Lights'),
/// trailing: CupertinoSwitch(
/// value: _lights,
/// onChanged: (bool value) { setState(() { _lights = value; }); },
/// ),
/// onTap: () { setState(() { _lights = !_lights; }); },
/// ),
/// )
/// ```
///
/// </callout-box>
///
/// See also:
///
/// * [Switch], the Material Design equivalent.
/// * <https://developer.apple.com/design/human-interface-guidelines/toggles/>
class CupertinoSwitch extends StatefulWidget {
/// Creates an iOS-style switch.
///
/// The following arguments are required:
///
/// * [value] determines whether this switch is on or off.
/// * [onChanged] is called when the user toggles the switch on or off.
///
/// The [dragStartBehavior] parameter defaults to [DragStartBehavior.start].
const CupertinoSwitch({
super.key,
required this.value,
required this.onChanged,
@Deprecated(
'Use activeTrackColor instead. '
'This feature was deprecated after v3.24.0-0.2.pre.',
)
Color? activeColor,
@Deprecated(
'Use inactiveTrackColor instead. '
'This feature was deprecated after v3.24.0-0.2.pre.',
)
Color? trackColor,
Color? activeTrackColor,
Color? inactiveTrackColor,
this.thumbColor,
this.inactiveThumbColor,
this.applyTheme,
this.focusColor,
this.onLabelColor,
this.offLabelColor,
this.activeThumbImage,
this.onActiveThumbImageError,
this.inactiveThumbImage,
this.onInactiveThumbImageError,
this.trackOutlineColor,
this.trackOutlineWidth,
this.thumbIcon,
this.mouseCursor,
this.focusNode,
this.onFocusChange,
this.autofocus = false,
this.dragStartBehavior = DragStartBehavior.start,
}) : assert(activeThumbImage != null || onActiveThumbImageError == null),
assert(inactiveThumbImage != null || onInactiveThumbImageError == null),
assert(activeTrackColor == null || activeColor == null),
assert(inactiveTrackColor == null || trackColor == null),
activeTrackColor = activeTrackColor ?? activeColor,
inactiveTrackColor = inactiveTrackColor ?? trackColor;
/// Whether this switch is on or off.
final bool value;
/// Called when the user toggles the switch on or off.
///
/// The switch passes the new value to the callback but does not actually
/// change state until the parent widget rebuilds the switch with the new
/// value.
///
/// If null, the switch will be displayed as disabled, which has a reduced opacity.
///
/// 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
/// CupertinoSwitch(
/// value: _giveVerse,
/// onChanged: (bool newValue) {
/// setState(() {
/// _giveVerse = newValue;
/// });
/// },
/// )
/// ```
final ValueChanged<bool>? onChanged;
/// The color to use for the track when the switch is on.
///
/// If null and [applyTheme] is false, defaults to [CupertinoColors.systemGreen]
/// in accordance to native iOS behavior. Otherwise, defaults to
/// [CupertinoThemeData.primaryColor].
///
/// See also:
///
/// * [inactiveTrackColor], the color to use for the track when the switch is off.
@Deprecated(
'Use activeTrackColor instead. '
'This feature was deprecated after v3.24.0-0.2.pre.',
)
Color? get activeColor => activeTrackColor;
/// The color to use for the track when the switch is on.
///
/// If null and [applyTheme] is false, defaults to [CupertinoColors.systemGreen]
/// in accordance to native iOS behavior. Otherwise, defaults to
/// [CupertinoThemeData.primaryColor].
///
/// See also:
///
/// * [inactiveTrackColor], the color to use for the track when the switch is off.
final Color? activeTrackColor;
/// The color to use for the track when the switch is off.
///
/// Defaults to [CupertinoColors.secondarySystemFill] when null.
///
/// See also:
///
/// * [inactiveTrackColor], the color to use for the track when the switch is off.
@Deprecated(
'Use inactiveTrackColor instead. '
'This feature was deprecated after v3.24.0-0.2.pre.',
)
Color? get trackColor => inactiveTrackColor;
/// The color to use for the track when the switch is off.
///
/// Defaults to [CupertinoColors.secondarySystemFill] when null.
///
/// See also:
///
/// * [activeTrackColor], the color to use for the track when the switch is on.
final Color? inactiveTrackColor;
/// The color to use for the thumb when the switch is on.
///
/// If this color is not opaque, it is blended against
/// [CupertinoThemeData.scaffoldBackgroundColor], so as not to see through the
/// thumb to the track underneath.
///
/// Defaults to [CupertinoColors.white] when null.
///
/// See also:
///
/// * [inactiveThumbColor], the color to use for the thumb when the switch is off.
final Color? thumbColor;
/// The color to use on the thumb when the switch is off.
///
/// If this color is not opaque, it is blended against
/// [CupertinoThemeData.scaffoldBackgroundColor], so as not to see through the
/// thumb to the track underneath.
///
/// If null, defaults to [thumbColor]. If that is also null,
/// [CupertinoColors.white] is used.
///
/// See also:
///
/// * [thumbColor], the color to use for the thumb when the switch is on.
final Color? inactiveThumbColor;
/// The color to use for the focus highlight for keyboard interactions.
///
/// Defaults to [activeColor] with an opacity of 0.80, a brightness of 0.69
/// and a saturation of 0.835.
final Color? focusColor;
/// The color to use for the accessibility label when the switch is on.
///
/// Defaults to [CupertinoColors.white] when null.
final Color? onLabelColor;
/// The color to use for the accessibility label when the switch is off.
///
/// Defaults to [Color.fromARGB(255, 179, 179, 179)]
/// (or [Color.fromARGB(255, 255, 255, 255)] in high contrast) when null.
final Color? offLabelColor;
/// {@template cupertino_ui.switch.activeThumbImage}
/// An image to use on the thumb of this switch when the switch is on.
/// {@endtemplate}
final ImageProvider? activeThumbImage;
/// {@template cupertino_ui.switch.onActiveThumbImageError}
/// An optional error callback for errors emitted when loading
/// [activeThumbImage].
/// {@endtemplate}
final ImageErrorListener? onActiveThumbImageError;
/// {@template cupertino_ui.switch.inactiveThumbImage}
/// An image to use on the thumb of this switch when the switch is off.
/// {@endtemplate}
final ImageProvider? inactiveThumbImage;
/// {@template cupertino_ui.switch.onInactiveThumbImageError}
/// An optional error callback for errors emitted when loading
/// [inactiveThumbImage].
/// {@endtemplate}
final ImageErrorListener? onInactiveThumbImageError;
/// The outline color of this [CupertinoSwitch]'s track.
///
/// Resolved in the following states:
/// * [WidgetState.selected].
/// * [WidgetState.hovered].
/// * [WidgetState.focused].
/// * [WidgetState.disabled].
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
/// This example resolves the [trackOutlineColor] based on the current
/// [WidgetState] of the [CupertinoSwitch], providing a different [Color] when it is
/// [WidgetState.disabled].
///
/// ```dart
/// CupertinoSwitch(
/// value: true,
/// onChanged: (bool value) { },
/// trackOutlineColor: WidgetStateProperty.resolveWith<Color?>((Set<WidgetState> states) {
/// if (states.contains(WidgetState.disabled)) {
/// return CupertinoColors.activeOrange.withValues(alpha: .48);
/// }
/// return null; // Use the default color.
/// }),
/// )
/// ```
///
/// </callout-box>
///
/// The [CupertinoSwitch] track has no outline by default.
final WidgetStateProperty<Color?>? trackOutlineColor;
/// The outline width of this [CupertinoSwitch]'s track.
///
/// Resolved in the following states:
/// * [WidgetState.selected].
/// * [WidgetState.hovered].
/// * [WidgetState.focused].
/// * [WidgetState.disabled].
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
/// This example resolves the [trackOutlineWidth] based on the current
/// [WidgetState] of the [CupertinoSwitch], providing a different outline width when it is
/// [WidgetState.disabled].
///
/// ```dart
/// CupertinoSwitch(
/// value: true,
/// onChanged: (bool value) { },
/// trackOutlineWidth: WidgetStateProperty.resolveWith<double?>((Set<WidgetState> states) {
/// if (states.contains(WidgetState.disabled)) {
/// return 5.0;
/// }
/// return null; // Use the default width.
/// }),
/// )
/// ```
///
/// </callout-box>
///
/// Since a [CupertinoSwitch] has no track outline by default, this parameter
/// is set only if [trackOutlineColor] is provided.
///
/// Defaults to 2.0 if a [trackOutlineColor] is provided.
final WidgetStateProperty<double?>? trackOutlineWidth;
/// The icon to use on the thumb of this switch.
///
/// Resolved in the following states:
/// * [WidgetState.selected].
/// * [WidgetState.hovered].
/// * [WidgetState.focused].
/// * [WidgetState.disabled].
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
/// This example resolves the [thumbIcon] based on the current
/// [WidgetState] of the [CupertinoSwitch], providing a different [Icon] when it is
/// [WidgetState.disabled].
///
/// ```dart
/// CupertinoSwitch(
/// value: true,
/// onChanged: (bool value) { },
/// thumbIcon: WidgetStateProperty.resolveWith<Icon?>((Set<WidgetState> states) {
/// if (states.contains(WidgetState.disabled)) {
/// return const Icon(Icons.close);
/// }
/// return null; // All other states will use the default thumbIcon.
/// }),
/// )
/// ```
///
/// </callout-box>
///
/// If null, then the [CupertinoSwitch] does not have any icons on the thumb.
final WidgetStateProperty<Icon?>? thumbIcon;
/// The cursor for a mouse pointer when it enters or is hovering over the
/// widget.
///
/// Resolved in the following states:
/// * [WidgetState.selected].
/// * [WidgetState.hovered].
/// * [WidgetState.focused].
/// * [WidgetState.disabled].
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
/// This example resolves the [mouseCursor] based on the current
/// [WidgetState] of the [CupertinoSwitch], providing a different [mouseCursor] when it is
/// [WidgetState.disabled].
///
/// ```dart
/// CupertinoSwitch(
/// value: true,
/// onChanged: (bool value) { },
/// mouseCursor: WidgetStateProperty.resolveWith<MouseCursor>((Set<WidgetState> states) {
/// if (states.contains(WidgetState.disabled)) {
/// return SystemMouseCursors.click;
/// }
/// return SystemMouseCursors.basic; // All other states will use the default mouseCursor.
/// }),
/// )
/// ```
///
/// </callout-box>
///
/// If null, then [MouseCursor.defer] is used when the switch is disabled.
/// When the switch is enabled, [SystemMouseCursors.click] is used on Web, and
/// [MouseCursor.defer] is used on other platforms.
///
/// See also:
///
/// * [WidgetStateMouseCursor], a [MouseCursor] that implements
/// `WidgetStateProperty` which is used in APIs that need to accept
/// either a [MouseCursor] or a [WidgetStateProperty].
final WidgetStateProperty<MouseCursor>? mouseCursor;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// Handler called when the focus changes.
///
/// Called with true if this widget's node gains focus, and false if it loses
/// focus.
final ValueChanged<bool>? onFocusChange;
/// {@macro flutter.widgets.Focus.autofocus}
final bool autofocus;
/// {@template cupertino_ui.CupertinoSwitch.applyTheme}
/// Whether to apply the ambient [CupertinoThemeData].
///
/// If true, the track uses [CupertinoThemeData.primaryColor] for the track
/// when the switch is on.
///
/// Defaults to [CupertinoThemeData.applyThemeToAll].
/// {@endtemplate}
final bool? applyTheme;
/// {@template cupertino_ui.CupertinoSwitch.dragStartBehavior}
/// Determines the way that drag start behavior is handled.
///
/// If set to [DragStartBehavior.start], the drag behavior used to move the
/// switch from on to off will begin at the position where the drag gesture won
/// the arena. If set to [DragStartBehavior.down] it will begin at the position
/// where a down event was first detected.
///
/// In general, setting this to [DragStartBehavior.start] will make drag
/// animation smoother and setting it to [DragStartBehavior.down] will make
/// drag behavior feel slightly more reactive.
///
/// By default, the drag start behavior is [DragStartBehavior.start].
///
/// See also:
///
/// * [DragGestureRecognizer.dragStartBehavior], which gives an example for
/// the different behaviors.
///
/// {@endtemplate}
final DragStartBehavior dragStartBehavior;
@override
State<CupertinoSwitch> createState() => _CupertinoSwitchState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(
FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true),
);
properties.add(
ObjectFlagProperty<ValueChanged<bool>>('onChanged', onChanged, ifNull: 'disabled'),
);
}
}
class _CupertinoSwitchState extends State<CupertinoSwitch>
with TickerProviderStateMixin, ToggleableStateMixin {
final _SwitchPainter _painter = _SwitchPainter();
// The global position where the user first touched the screen. This value to
// calculate the initial drag delta.
Offset _dragStartPosition = Offset.zero;
// The cumulative horizontal drag delta, normalized as a fraction of the
// track width.
double _dragDelta = 0;
// The transient value of the switch determined by _dragDelta during a
// drag.
bool? _dragValue;
@override
void initState() {
super.initState();
positionController.duration = const Duration(milliseconds: 200);
reactionController.duration = const Duration(milliseconds: 300);
position
..curve = Curves.ease
..reverseCurve = Curves.ease.flipped;
}
@override
void didUpdateWidget(CupertinoSwitch oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.value != widget.value) {
animateToValue();
}
}
@override
void dispose() {
_painter.dispose();
super.dispose();
}
@override
ValueChanged<bool?>? get onChanged => widget.onChanged != null ? _handleChanged : null;
@override
bool get tristate => false;
@override
bool? get value => widget.value;
WidgetStateProperty<Color?> get _widgetThumbColor {
return WidgetStateProperty.resolveWith((Set<WidgetState> states) {
if (states.contains(WidgetState.selected)) {
return widget.thumbColor;
}
return widget.inactiveThumbColor;
});
}
WidgetStateProperty<Color?> get _widgetTrackColor {
return WidgetStateProperty.resolveWith((Set<WidgetState> states) {
if (states.contains(WidgetState.selected)) {
return widget.activeTrackColor;
}
return widget.inactiveTrackColor;
});
}
WidgetStateProperty<MouseCursor> get _defaultMouseCursor =>
WidgetStateProperty.resolveWith((Set<WidgetState> states) {
if (states.contains(WidgetState.disabled)) {
return MouseCursor.defer;
}
return kIsWeb ? SystemMouseCursors.click : MouseCursor.defer;
});
Color? _resolveTrackColor(Color? trackColor, Set<WidgetState> states) {
if (trackColor is WidgetStateColor) {
return WidgetStateProperty.resolveAs<Color?>(trackColor, states);
}
return trackColor;
}
Color? _resolveThumbColor(Color? thumbColor, Set<WidgetState> states) {
if (thumbColor is WidgetStateColor) {
return WidgetStateProperty.resolveAs<Color?>(thumbColor, states);
}
return thumbColor;
}
double get _trackInnerLength {
const double trackInnerStart = _kTrackHeight / 2.0;
const double trackInnerEnd = _kTrackWidth - trackInnerStart;
const double trackInnerLength = trackInnerEnd - trackInnerStart;
return trackInnerLength;
}
void _handleOnTapDown(TapDownDetails details) {
if (isInteractive) {
_dragStartPosition = details.globalPosition;
}
}
void _handleDragStart(DragStartDetails details) {
if (isInteractive) {
reactionController.forward();
if (_dragStartPosition != Offset.zero) {
final double delta = (details.globalPosition - _dragStartPosition).dx / _kTrackWidth;
_dragDelta = switch (Directionality.of(context)) {
TextDirection.rtl => -delta,
TextDirection.ltr => delta,
};
}
_dragValue = value;
}
}
void _handleDragUpdate(DragUpdateDetails details) {
if (isInteractive) {
final double delta = details.primaryDelta! / _kTrackWidth;
_dragDelta += switch (Directionality.of(context)) {
TextDirection.rtl => -delta,
TextDirection.ltr => delta,
};
final valueChangedWhileDragging = widget.value != _dragValue;
final double threshold = valueChangedWhileDragging
? _kDragReverseThreshold
: _kDragCommitThreshold;
final double effectiveThreshold = widget.value ? -threshold : threshold;
final bool newDragValue = _dragDelta >= effectiveThreshold;
if (_dragValue != newDragValue) {
_emitVibration();
if (newDragValue) {
positionController.forward();
} else {
positionController.reverse();
}
_dragValue = newDragValue;
}
}
}
bool _needsPositionAnimation = false;
void _handleDragEnd(DragEndDetails details) {
if (_dragValue != widget.value) {
widget.onChanged?.call(!widget.value);
// Wait to finish the animation until widget.value has changed to
// !widget.value as part of the widget.onChanged call above.
setState(() {
_needsPositionAnimation = true;
});
}
_dragStartPosition = Offset.zero;
_dragDelta = 0;
_dragValue = null;
reactionController.reverse();
}
void _handleChanged(bool? value) {
assert(value != null);
assert(widget.onChanged != null);
widget.onChanged?.call(value!);
_emitVibration();
}
void _emitVibration() {
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
HapticFeedback.lightImpact();
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
break;
}
}
@override
Widget build(BuildContext context) {
if (_needsPositionAnimation) {
_needsPositionAnimation = false;
animateToValue();
}
final CupertinoThemeData theme = CupertinoTheme.of(context);
final Color activeColor = CupertinoDynamicColor.resolve(
widget.activeTrackColor ??
((widget.applyTheme ?? theme.applyThemeToAll) ? theme.primaryColor : null) ??
CupertinoColors.systemGreen,
context,
);
final (Color onLabelColor, Color offLabelColor)? onOffLabelColors =
MediaQuery.onOffSwitchLabelsOf(context)
? (
CupertinoDynamicColor.resolve(widget.onLabelColor ?? CupertinoColors.white, context),
CupertinoDynamicColor.resolve(widget.offLabelColor ?? _kOffLabelColor, context),
)
: null;
// Colors need to be resolved in selected and non selected states separately
// so that they can be lerped between.
final Set<WidgetState> activeStates = states..add(WidgetState.selected);
final Set<WidgetState> inactiveStates = states..remove(WidgetState.selected);
final Color effectiveActiveThumbColor =
_resolveThumbColor(widget.thumbColor, activeStates) ??
_widgetThumbColor.resolve(activeStates) ??
CupertinoColors.white;
final Color effectiveInactiveThumbColor =
_resolveThumbColor(widget.inactiveThumbColor, inactiveStates) ??
_widgetThumbColor.resolve(inactiveStates) ??
effectiveActiveThumbColor;
final Color effectiveActiveTrackColor = _widgetTrackColor.resolve(activeStates) ?? activeColor;
final Color? effectiveActiveTrackOutlineColor = widget.trackOutlineColor?.resolve(activeStates);
final double? effectiveActiveTrackOutlineWidth = widget.trackOutlineWidth?.resolve(
activeStates,
);
final Color effectiveInactiveTrackColor =
_resolveTrackColor(widget.trackColor, inactiveStates) ??
CupertinoDynamicColor.resolve(CupertinoColors.secondarySystemFill, context);
final Color? effectiveInactiveTrackOutlineColor = widget.trackOutlineColor?.resolve(
inactiveStates,
);
final double? effectiveInactiveTrackOutlineWidth = widget.trackOutlineWidth?.resolve(
inactiveStates,
);
final Icon? effectiveActiveIcon = widget.thumbIcon?.resolve(activeStates);
final Icon? effectiveInactiveIcon = widget.thumbIcon?.resolve(inactiveStates);
final Color effectiveActiveIconColor = effectiveActiveIcon?.color ?? CupertinoColors.black;
final Color effectiveInactiveIconColor = effectiveInactiveIcon?.color ?? CupertinoColors.black;
final activePressedStates = activeStates..add(WidgetState.pressed);
final Color effectiveActivePressedThumbColor =
_resolveThumbColor(widget.thumbColor, activePressedStates) ??
_widgetThumbColor.resolve(activePressedStates) ??
CupertinoColors.white;
final inactivePressedStates = inactiveStates..add(WidgetState.pressed);
final Color effectiveInactivePressedThumbColor =
_resolveThumbColor(widget.thumbColor, inactivePressedStates) ??
_widgetThumbColor.resolve(inactivePressedStates) ??
CupertinoColors.white;
final WidgetStateProperty<MouseCursor> effectiveMouseCursor =
widget.mouseCursor ?? _defaultMouseCursor;
return Semantics(
toggled: widget.value,
child: GestureDetector(
excludeFromSemantics: true,
onTapDown: _handleOnTapDown,
onHorizontalDragStart: _handleDragStart,
onHorizontalDragUpdate: _handleDragUpdate,
onHorizontalDragEnd: _handleDragEnd,
dragStartBehavior: widget.dragStartBehavior,
child: Opacity(
opacity: onChanged == null ? _kDisabledOpacity : 1,
child: buildToggleable(
mouseCursor: effectiveMouseCursor,
focusNode: widget.focusNode,
onFocusChange: widget.onFocusChange,
autofocus: widget.autofocus,
size: _kSwitchSize,
painter: _painter
..position = position
..reaction = reaction
..reactionFocusFade = reactionFocusFade
..reactionHoverFade = reactionHoverFade
..focusColor = CupertinoDynamicColor.resolve(
widget.focusColor ??
HSLColor.fromColor(activeColor.withOpacity(kCupertinoFocusColorOpacity))
.withLightness(kCupertinoFocusColorBrightness)
.withSaturation(kCupertinoFocusColorSaturation)
.toColor(),
context,
)
..downPosition = downPosition
..isFocused = states.contains(WidgetState.focused)
..isHovered = states.contains(WidgetState.hovered)
..activeColor = effectiveActiveThumbColor
..inactiveColor = effectiveInactiveThumbColor
..activePressedColor = effectiveActivePressedThumbColor
..onOffLabelColors = onOffLabelColors
..inactivePressedColor = effectiveInactivePressedThumbColor
..activeThumbImage = widget.activeThumbImage
..onActiveThumbImageError = widget.onActiveThumbImageError
..inactiveThumbImage = widget.inactiveThumbImage
..onInactiveThumbImageError = widget.onInactiveThumbImageError
..activeTrackColor = effectiveActiveTrackColor
..activeTrackOutlineColor = effectiveActiveTrackOutlineColor
..activeTrackOutlineWidth = effectiveActiveTrackOutlineWidth
..inactiveTrackColor = effectiveInactiveTrackColor
..inactiveTrackOutlineColor = effectiveInactiveTrackOutlineColor
..inactiveTrackOutlineWidth = effectiveInactiveTrackOutlineWidth
..configuration = createLocalImageConfiguration(context)
..isInteractive = isInteractive
..trackInnerLength = _trackInnerLength
..textDirection = Directionality.of(context)
..activeIconColor = effectiveActiveIconColor
..inactiveIconColor = effectiveInactiveIconColor
..activeIcon = effectiveActiveIcon
..inactiveIcon = effectiveInactiveIcon
..iconTheme = IconTheme.of(context)
..surfaceColor = theme.scaffoldBackgroundColor
..positionController = positionController,
),
),
),
);
}
}
class _SwitchPainter extends ToggleablePainter {
AnimationController get positionController => _positionController!;
AnimationController? _positionController;
set positionController(AnimationController value) {
if (value == _positionController) {
return;
}
_positionController = value;
_colorAnimation?.dispose();
_colorAnimation = CurvedAnimation(
parent: positionController,
curve: Curves.easeOut,
reverseCurve: Curves.easeIn,
);
notifyListeners();
}
CurvedAnimation? _colorAnimation;
Icon? get activeIcon => _activeIcon;
Icon? _activeIcon;
set activeIcon(Icon? value) {
if (value == _activeIcon) {
return;
}
_activeIcon = value;
notifyListeners();
}
Icon? get inactiveIcon => _inactiveIcon;
Icon? _inactiveIcon;
set inactiveIcon(Icon? value) {
if (value == _inactiveIcon) {
return;
}
_inactiveIcon = value;
notifyListeners();
}
IconThemeData? get iconTheme => _iconTheme;
IconThemeData? _iconTheme;
set iconTheme(IconThemeData? value) {
if (value == _iconTheme) {
return;
}
_iconTheme = value;
notifyListeners();
}
Color get activeIconColor => _activeIconColor!;
Color? _activeIconColor;
set activeIconColor(Color value) {
if (value == _activeIconColor) {
return;
}
_activeIconColor = value;
notifyListeners();
}
Color get inactiveIconColor => _inactiveIconColor!;
Color? _inactiveIconColor;
set inactiveIconColor(Color value) {
if (value == _inactiveIconColor) {
return;
}
_inactiveIconColor = value;
notifyListeners();
}
Color get activePressedColor => _activePressedColor!;
Color? _activePressedColor;
set activePressedColor(Color value) {
if (value == _activePressedColor) {
return;
}
_activePressedColor = value;
notifyListeners();
}
Color get inactivePressedColor => _inactivePressedColor!;
Color? _inactivePressedColor;
set inactivePressedColor(Color value) {
if (value == _inactivePressedColor) {
return;
}
_inactivePressedColor = value;
notifyListeners();
}
ImageProvider? get activeThumbImage => _activeThumbImage;
ImageProvider? _activeThumbImage;
set activeThumbImage(ImageProvider? value) {
if (value == _activeThumbImage) {
return;
}
_activeThumbImage = value;
notifyListeners();
}
ImageErrorListener? get onActiveThumbImageError => _onActiveThumbImageError;
ImageErrorListener? _onActiveThumbImageError;
set onActiveThumbImageError(ImageErrorListener? value) {
if (value == _onActiveThumbImageError) {
return;
}
_onActiveThumbImageError = value;
notifyListeners();
}
ImageProvider? get inactiveThumbImage => _inactiveThumbImage;
ImageProvider? _inactiveThumbImage;
set inactiveThumbImage(ImageProvider? value) {
if (value == _inactiveThumbImage) {
return;
}
_inactiveThumbImage = value;
notifyListeners();
}
ImageErrorListener? get onInactiveThumbImageError => _onInactiveThumbImageError;
ImageErrorListener? _onInactiveThumbImageError;
set onInactiveThumbImageError(ImageErrorListener? value) {
if (value == _onInactiveThumbImageError) {
return;
}
_onInactiveThumbImageError = value;
notifyListeners();
}
Color get activeTrackColor => _activeTrackColor!;
Color? _activeTrackColor;
set activeTrackColor(Color value) {
if (value == _activeTrackColor) {
return;
}
_activeTrackColor = value;
notifyListeners();
}