This repository has been archived by the owner on Feb 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
switch.dart
611 lines (543 loc) · 18.5 KB
/
switch.dart
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
// 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.
// Examples can assume:
// bool _giveVerse = false;
import 'dart:ui' show lerpDouble;
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 'theme.dart';
import 'thumb_painter.dart';
// Examples can assume:
// bool _lights = false;
// void setState(VoidCallback fn) { }
/// An iOS-style switch.
///
/// Used to toggle the on/off state of a single setting.
///
/// The switch itself does not maintain any state. Instead, when the 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.
///
/// {@tool dartpad}
/// This example shows a toggleable [CupertinoSwitch]. When the thumb slides to
/// the other side of the track, the switch is toggled between on/off.
///
/// ** See code in examples/api/lib/cupertino/switch/cupertino_switch.0.dart **
/// {@end-tool}
///
/// {@tool snippet}
///
/// This sample shows how to use a [CupertinoSwitch] in a [ListTile]. The
/// [MergeSemantics] is used to turn the entire [ListTile] into a single item
/// for accessibility tools.
///
/// ```dart
/// MergeSemantics(
/// child: ListTile(
/// title: const Text('Lights'),
/// trailing: CupertinoSwitch(
/// value: _lights,
/// onChanged: (bool value) { setState(() { _lights = value; }); },
/// ),
/// onTap: () { setState(() { _lights = !_lights; }); },
/// ),
/// )
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [Switch], the Material Design equivalent.
/// * <https://developer.apple.com/ios/human-interface-guidelines/controls/switches/>
class CupertinoSwitch extends StatefulWidget {
/// Creates an iOS-style switch.
///
/// The [value] parameter must not be null.
/// The [dragStartBehavior] parameter defaults to [DragStartBehavior.start] and must not be null.
const CupertinoSwitch({
super.key,
required this.value,
required this.onChanged,
this.activeColor,
this.trackColor,
this.thumbColor,
this.applyTheme,
this.dragStartBehavior = DragStartBehavior.start,
}) : assert(value != null),
assert(dragStartBehavior != null);
/// Whether this switch is on or off.
///
/// Must not be null.
final bool value;
/// Called when the user toggles with 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].
final Color? activeColor;
/// The color to use for the track when the switch is off.
///
/// Defaults to [CupertinoColors.secondarySystemFill] when null.
final Color? trackColor;
/// The color to use for the thumb of the switch.
///
/// Defaults to [CupertinoColors.white] when null.
final Color? thumbColor;
/// {@template flutter.cupertino.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 flutter.cupertino.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 {
late TapGestureRecognizer _tap;
late HorizontalDragGestureRecognizer _drag;
late AnimationController _positionController;
late CurvedAnimation position;
late AnimationController _reactionController;
late Animation<double> _reaction;
bool get isInteractive => widget.onChanged != null;
// A non-null boolean value that changes to true at the end of a drag if the
// switch must be animated to the position indicated by the widget's value.
bool needsPositionAnimation = false;
@override
void initState() {
super.initState();
_tap = TapGestureRecognizer()
..onTapDown = _handleTapDown
..onTapUp = _handleTapUp
..onTap = _handleTap
..onTapCancel = _handleTapCancel;
_drag = HorizontalDragGestureRecognizer()
..onStart = _handleDragStart
..onUpdate = _handleDragUpdate
..onEnd = _handleDragEnd
..dragStartBehavior = widget.dragStartBehavior;
_positionController = AnimationController(
duration: _kToggleDuration,
value: widget.value ? 1.0 : 0.0,
vsync: this,
);
position = CurvedAnimation(
parent: _positionController,
curve: Curves.linear,
);
_reactionController = AnimationController(
duration: _kReactionDuration,
vsync: this,
);
_reaction = CurvedAnimation(
parent: _reactionController,
curve: Curves.ease,
);
}
@override
void didUpdateWidget(CupertinoSwitch oldWidget) {
super.didUpdateWidget(oldWidget);
_drag.dragStartBehavior = widget.dragStartBehavior;
if (needsPositionAnimation || oldWidget.value != widget.value) {
_resumePositionAnimation(isLinear: needsPositionAnimation);
}
}
// `isLinear` must be true if the position animation is trying to move the
// thumb to the closest end after the most recent drag animation, so the curve
// does not change when the controller's value is not 0 or 1.
//
// It can be set to false when it's an implicit animation triggered by
// widget.value changes.
void _resumePositionAnimation({ bool isLinear = true }) {
needsPositionAnimation = false;
position
..curve = isLinear ? Curves.linear : Curves.ease
..reverseCurve = isLinear ? Curves.linear : Curves.ease.flipped;
if (widget.value) {
_positionController.forward();
} else {
_positionController.reverse();
}
}
void _handleTapDown(TapDownDetails details) {
if (isInteractive) {
needsPositionAnimation = false;
}
_reactionController.forward();
}
void _handleTap() {
if (isInteractive) {
widget.onChanged!(!widget.value);
_emitVibration();
}
}
void _handleTapUp(TapUpDetails details) {
if (isInteractive) {
needsPositionAnimation = false;
_reactionController.reverse();
}
}
void _handleTapCancel() {
if (isInteractive) {
_reactionController.reverse();
}
}
void _handleDragStart(DragStartDetails details) {
if (isInteractive) {
needsPositionAnimation = false;
_reactionController.forward();
_emitVibration();
}
}
void _handleDragUpdate(DragUpdateDetails details) {
if (isInteractive) {
position
..curve = Curves.linear
..reverseCurve = Curves.linear;
final double delta = details.primaryDelta! / _kTrackInnerLength;
switch (Directionality.of(context)) {
case TextDirection.rtl:
_positionController.value -= delta;
break;
case TextDirection.ltr:
_positionController.value += delta;
break;
}
}
}
void _handleDragEnd(DragEndDetails details) {
// Deferring the animation to the next build phase.
setState(() { needsPositionAnimation = true; });
// Call onChanged when the user's intent to change value is clear.
if (position.value >= 0.5 != widget.value) {
widget.onChanged!(!widget.value);
}
_reactionController.reverse();
}
void _emitVibration() {
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
HapticFeedback.lightImpact();
break;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
break;
}
}
@override
Widget build(BuildContext context) {
final CupertinoThemeData theme = CupertinoTheme.of(context);
if (needsPositionAnimation) {
_resumePositionAnimation();
}
return MouseRegion(
cursor: isInteractive && kIsWeb ? SystemMouseCursors.click : MouseCursor.defer,
child: Opacity(
opacity: widget.onChanged == null ? _kCupertinoSwitchDisabledOpacity : 1.0,
child: _CupertinoSwitchRenderObjectWidget(
value: widget.value,
activeColor: CupertinoDynamicColor.resolve(
widget.activeColor
?? ((widget.applyTheme ?? theme.applyThemeToAll) ? theme.primaryColor : null)
?? CupertinoColors.systemGreen,
context,
),
trackColor: CupertinoDynamicColor.resolve(widget.trackColor ?? CupertinoColors.secondarySystemFill, context),
thumbColor: CupertinoDynamicColor.resolve(widget.thumbColor ?? CupertinoColors.white, context),
onChanged: widget.onChanged,
textDirection: Directionality.of(context),
state: this,
),
),
);
}
@override
void dispose() {
_tap.dispose();
_drag.dispose();
_positionController.dispose();
_reactionController.dispose();
super.dispose();
}
}
class _CupertinoSwitchRenderObjectWidget extends LeafRenderObjectWidget {
const _CupertinoSwitchRenderObjectWidget({
required this.value,
required this.activeColor,
required this.trackColor,
required this.thumbColor,
required this.onChanged,
required this.textDirection,
required this.state,
});
final bool value;
final Color activeColor;
final Color trackColor;
final Color thumbColor;
final ValueChanged<bool>? onChanged;
final _CupertinoSwitchState state;
final TextDirection textDirection;
@override
_RenderCupertinoSwitch createRenderObject(BuildContext context) {
return _RenderCupertinoSwitch(
value: value,
activeColor: activeColor,
trackColor: trackColor,
thumbColor: thumbColor,
onChanged: onChanged,
textDirection: textDirection,
state: state,
);
}
@override
void updateRenderObject(BuildContext context, _RenderCupertinoSwitch renderObject) {
assert(renderObject._state == state);
renderObject
..value = value
..activeColor = activeColor
..trackColor = trackColor
..thumbColor = thumbColor
..onChanged = onChanged
..textDirection = textDirection;
}
}
const double _kTrackWidth = 51.0;
const double _kTrackHeight = 31.0;
const double _kTrackRadius = _kTrackHeight / 2.0;
const double _kTrackInnerStart = _kTrackHeight / 2.0;
const double _kTrackInnerEnd = _kTrackWidth - _kTrackInnerStart;
const double _kTrackInnerLength = _kTrackInnerEnd - _kTrackInnerStart;
const double _kSwitchWidth = 59.0;
const double _kSwitchHeight = 39.0;
// Opacity of a disabled switch, as eye-balled from iOS Simulator on Mac.
const double _kCupertinoSwitchDisabledOpacity = 0.5;
const Duration _kReactionDuration = Duration(milliseconds: 300);
const Duration _kToggleDuration = Duration(milliseconds: 200);
class _RenderCupertinoSwitch extends RenderConstrainedBox {
_RenderCupertinoSwitch({
required bool value,
required Color activeColor,
required Color trackColor,
required Color thumbColor,
ValueChanged<bool>? onChanged,
required TextDirection textDirection,
required _CupertinoSwitchState state,
}) : assert(value != null),
assert(activeColor != null),
assert(state != null),
_value = value,
_activeColor = activeColor,
_trackColor = trackColor,
_thumbPainter = CupertinoThumbPainter.switchThumb(color: thumbColor),
_onChanged = onChanged,
_textDirection = textDirection,
_state = state,
super(additionalConstraints: const BoxConstraints.tightFor(width: _kSwitchWidth, height: _kSwitchHeight)) {
state.position.addListener(markNeedsPaint);
state._reaction.addListener(markNeedsPaint);
}
final _CupertinoSwitchState _state;
bool get value => _value;
bool _value;
set value(bool value) {
assert(value != null);
if (value == _value) {
return;
}
_value = value;
markNeedsSemanticsUpdate();
}
Color get activeColor => _activeColor;
Color _activeColor;
set activeColor(Color value) {
assert(value != null);
if (value == _activeColor) {
return;
}
_activeColor = value;
markNeedsPaint();
}
Color get trackColor => _trackColor;
Color _trackColor;
set trackColor(Color value) {
assert(value != null);
if (value == _trackColor) {
return;
}
_trackColor = value;
markNeedsPaint();
}
Color get thumbColor => _thumbPainter.color;
CupertinoThumbPainter _thumbPainter;
set thumbColor(Color value) {
assert(value != null);
if (value == thumbColor) {
return;
}
_thumbPainter = CupertinoThumbPainter.switchThumb(color: value);
markNeedsPaint();
}
ValueChanged<bool>? get onChanged => _onChanged;
ValueChanged<bool>? _onChanged;
set onChanged(ValueChanged<bool>? value) {
if (value == _onChanged) {
return;
}
final bool wasInteractive = isInteractive;
_onChanged = value;
if (wasInteractive != isInteractive) {
markNeedsPaint();
markNeedsSemanticsUpdate();
}
}
TextDirection get textDirection => _textDirection;
TextDirection _textDirection;
set textDirection(TextDirection value) {
assert(value != null);
if (_textDirection == value) {
return;
}
_textDirection = value;
markNeedsPaint();
}
bool get isInteractive => onChanged != null;
@override
bool hitTestSelf(Offset position) => true;
@override
void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
assert(debugHandleEvent(event, entry));
if (event is PointerDownEvent && isInteractive) {
_state._drag.addPointer(event);
_state._tap.addPointer(event);
}
}
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
super.describeSemanticsConfiguration(config);
if (isInteractive) {
config.onTap = _state._handleTap;
}
config.isEnabled = isInteractive;
config.isToggled = _value;
}
@override
void paint(PaintingContext context, Offset offset) {
final Canvas canvas = context.canvas;
final double currentValue = _state.position.value;
final double currentReactionValue = _state._reaction.value;
final double visualPosition;
switch (textDirection) {
case TextDirection.rtl:
visualPosition = 1.0 - currentValue;
break;
case TextDirection.ltr:
visualPosition = currentValue;
break;
}
final Paint paint = Paint()
..color = Color.lerp(trackColor, activeColor, currentValue)!;
final Rect trackRect = Rect.fromLTWH(
offset.dx + (size.width - _kTrackWidth) / 2.0,
offset.dy + (size.height - _kTrackHeight) / 2.0,
_kTrackWidth,
_kTrackHeight,
);
final RRect trackRRect = RRect.fromRectAndRadius(trackRect, const Radius.circular(_kTrackRadius));
canvas.drawRRect(trackRRect, paint);
final double currentThumbExtension = CupertinoThumbPainter.extension * currentReactionValue;
final double thumbLeft = lerpDouble(
trackRect.left + _kTrackInnerStart - CupertinoThumbPainter.radius,
trackRect.left + _kTrackInnerEnd - CupertinoThumbPainter.radius - currentThumbExtension,
visualPosition,
)!;
final double thumbRight = lerpDouble(
trackRect.left + _kTrackInnerStart + CupertinoThumbPainter.radius + currentThumbExtension,
trackRect.left + _kTrackInnerEnd + CupertinoThumbPainter.radius,
visualPosition,
)!;
final double thumbCenterY = offset.dy + size.height / 2.0;
final Rect thumbBounds = Rect.fromLTRB(
thumbLeft,
thumbCenterY - CupertinoThumbPainter.radius,
thumbRight,
thumbCenterY + CupertinoThumbPainter.radius,
);
_clipRRectLayer.layer = context.pushClipRRect(needsCompositing, Offset.zero, thumbBounds, trackRRect, (PaintingContext innerContext, Offset offset) {
_thumbPainter.paint(innerContext.canvas, thumbBounds);
}, oldLayer: _clipRRectLayer.layer);
}
final LayerHandle<ClipRRectLayer> _clipRRectLayer = LayerHandle<ClipRRectLayer>();
@override
void dispose() {
_clipRRectLayer.layer = null;
super.dispose();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder description) {
super.debugFillProperties(description);
description.add(FlagProperty('value', value: value, ifTrue: 'checked', ifFalse: 'unchecked', showName: true));
description.add(FlagProperty('isInteractive', value: isInteractive, ifTrue: 'enabled', ifFalse: 'disabled', showName: true, defaultValue: true));
}
}