switch.dart 17.8 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:ui' show lerpDouble;

xster's avatar
xster committed
7
import 'package:flutter/foundation.dart';
8 9
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
10
import 'package:flutter/services.dart';
11
import 'package:flutter/widgets.dart';
12

xster's avatar
xster committed
13
import 'colors.dart';
14 15
import 'thumb_painter.dart';

16
// Examples can assume:
17
// bool _lights = false;
18 19
// void setState(VoidCallback fn) { }

20 21 22 23 24 25 26 27 28
/// 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.
///
29 30 31 32 33 34 35
/// {@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}
///
36
/// {@tool snippet}
37 38 39 40 41 42
///
/// 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
43 44
/// MergeSemantics(
///   child: ListTile(
45
///     title: const Text('Lights'),
46
///     trailing: CupertinoSwitch(
47 48 49 50 51 52 53
///       value: _lights,
///       onChanged: (bool value) { setState(() { _lights = value; }); },
///     ),
///     onTap: () { setState(() { _lights = !_lights; }); },
///   ),
/// )
/// ```
54
/// {@end-tool}
55
///
56 57
/// See also:
///
58
///  * [Switch], the Material Design equivalent.
59
///  * <https://developer.apple.com/ios/human-interface-guidelines/controls/switches/>
60
class CupertinoSwitch extends StatefulWidget {
Adam Barth's avatar
Adam Barth committed
61
  /// Creates an iOS-style switch.
62
  ///
63 64
  /// The [value] parameter must not be null.
  /// The [dragStartBehavior] parameter defaults to [DragStartBehavior.start] and must not be null.
65
  const CupertinoSwitch({
66
    super.key,
67 68
    required this.value,
    required this.onChanged,
69
    this.activeColor,
70
    this.trackColor,
71
    this.thumbColor,
72
    this.dragStartBehavior = DragStartBehavior.start,
73
  }) : assert(value != null),
74
       assert(dragStartBehavior != null);
75 76

  /// Whether this switch is on or off.
77 78
  ///
  /// Must not be null.
79 80 81 82 83 84 85 86
  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.
  ///
87
  /// If null, the switch will be displayed as disabled, which has a reduced opacity.
88 89 90 91 92 93
  ///
  /// 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
94
  /// CupertinoSwitch(
95 96 97 98 99 100
  ///   value: _giveVerse,
  ///   onChanged: (bool newValue) {
  ///     setState(() {
  ///       _giveVerse = newValue;
  ///     });
  ///   },
101
  /// )
102
  /// ```
103
  final ValueChanged<bool>? onChanged;
104 105

  /// The color to use when this switch is on.
106
  ///
107
  /// Defaults to [CupertinoColors.systemGreen] when null and ignores
108
  /// the [CupertinoTheme] in accordance to native iOS behavior.
109
  final Color? activeColor;
110

111 112 113
  /// The color to use for the background when the switch is off.
  ///
  /// Defaults to [CupertinoColors.secondarySystemFill] when null.
114
  final Color? trackColor;
115

116 117 118 119 120
  /// The color to use for the thumb of the switch.
  ///
  /// Defaults to [CupertinoColors.white] when null.
  final Color? thumbColor;

121
  /// {@template flutter.cupertino.CupertinoSwitch.dragStartBehavior}
122 123 124
  /// Determines the way that drag start behavior is handled.
  ///
  /// If set to [DragStartBehavior.start], the drag behavior used to move the
125 126 127
  /// 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.
128 129 130 131 132
  ///
  /// 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.
  ///
133
  /// By default, the drag start behavior is [DragStartBehavior.start].
134 135 136
  ///
  /// See also:
  ///
137 138 139
  ///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for
  ///    the different behaviors.
  ///
140 141 142
  /// {@endtemplate}
  final DragStartBehavior dragStartBehavior;

143
  @override
144
  State<CupertinoSwitch> createState() => _CupertinoSwitchState();
145 146

  @override
147 148
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
149 150
    properties.add(FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true));
    properties.add(ObjectFlagProperty<ValueChanged<bool>>('onChanged', onChanged, ifNull: 'disabled'));
151 152 153 154
  }
}

class _CupertinoSwitchState extends State<CupertinoSwitch> with TickerProviderStateMixin {
155 156
  late TapGestureRecognizer _tap;
  late HorizontalDragGestureRecognizer _drag;
157

158 159
  late AnimationController _positionController;
  late CurvedAnimation position;
160

161 162
  late AnimationController _reactionController;
  late Animation<double> _reaction;
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

  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;

209
    if (needsPositionAnimation || oldWidget.value != widget.value) {
210
      _resumePositionAnimation(isLinear: needsPositionAnimation);
211
    }
212 213 214 215 216 217 218 219 220 221 222
  }

  // `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
223 224
      ..curve = isLinear ? Curves.linear : Curves.ease
      ..reverseCurve = isLinear ? Curves.linear : Curves.ease.flipped;
225
    if (widget.value) {
226
      _positionController.forward();
227
    } else {
228
      _positionController.reverse();
229
    }
230 231 232
  }

  void _handleTapDown(TapDownDetails details) {
233
    if (isInteractive) {
234
      needsPositionAnimation = false;
235
    }
236 237 238 239 240
      _reactionController.forward();
  }

  void _handleTap() {
    if (isInteractive) {
241
      widget.onChanged!(!widget.value);
242 243 244 245 246 247 248 249 250 251 252 253
      _emitVibration();
    }
  }

  void _handleTapUp(TapUpDetails details) {
    if (isInteractive) {
      needsPositionAnimation = false;
      _reactionController.reverse();
    }
  }

  void _handleTapCancel() {
254
    if (isInteractive) {
255
      _reactionController.reverse();
256
    }
257 258 259 260 261 262 263 264 265 266 267 268 269
  }

  void _handleDragStart(DragStartDetails details) {
    if (isInteractive) {
      needsPositionAnimation = false;
      _reactionController.forward();
      _emitVibration();
    }
  }

  void _handleDragUpdate(DragUpdateDetails details) {
    if (isInteractive) {
      position
270 271 272
        ..curve = Curves.linear
        ..reverseCurve = Curves.linear;
      final double delta = details.primaryDelta! / _kTrackInnerLength;
273
      switch (Directionality.of(context)) {
274 275 276 277 278 279 280 281 282 283 284 285 286 287
        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.
288
    if (position.value >= 0.5 != widget.value) {
289
      widget.onChanged!(!widget.value);
290
    }
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    _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;
    }
  }

308 309
  @override
  Widget build(BuildContext context) {
310
    if (needsPositionAnimation) {
311
      _resumePositionAnimation();
312
    }
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    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 ?? 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,
328
        ),
329
      ),
330 331
    );
  }
332 333 334 335 336 337 338 339 340 341

  @override
  void dispose() {
    _tap.dispose();
    _drag.dispose();

    _positionController.dispose();
    _reactionController.dispose();
    super.dispose();
  }
342 343 344
}

class _CupertinoSwitchRenderObjectWidget extends LeafRenderObjectWidget {
345
  const _CupertinoSwitchRenderObjectWidget({
346 347 348
    required this.value,
    required this.activeColor,
    required this.trackColor,
349
    required this.thumbColor,
350 351 352
    required this.onChanged,
    required this.textDirection,
    required this.state,
353
  });
354 355 356

  final bool value;
  final Color activeColor;
357
  final Color trackColor;
358
  final Color thumbColor;
359
  final ValueChanged<bool>? onChanged;
360 361
  final _CupertinoSwitchState state;
  final TextDirection textDirection;
362 363 364

  @override
  _RenderCupertinoSwitch createRenderObject(BuildContext context) {
365
    return _RenderCupertinoSwitch(
366 367
      value: value,
      activeColor: activeColor,
368
      trackColor: trackColor,
369
      thumbColor: thumbColor,
370
      onChanged: onChanged,
371 372
      textDirection: textDirection,
      state: state,
373 374 375 376 377 378 379 380
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderCupertinoSwitch renderObject) {
    renderObject
      ..value = value
      ..activeColor = activeColor
381
      ..trackColor = trackColor
382
      ..thumbColor = thumbColor
383
      ..onChanged = onChanged
384
      ..textDirection = textDirection;
385 386 387
  }
}

388 389
const double _kTrackWidth = 51.0;
const double _kTrackHeight = 31.0;
390 391 392 393
const double _kTrackRadius = _kTrackHeight / 2.0;
const double _kTrackInnerStart = _kTrackHeight / 2.0;
const double _kTrackInnerEnd = _kTrackWidth - _kTrackInnerStart;
const double _kTrackInnerLength = _kTrackInnerEnd - _kTrackInnerStart;
394 395
const double _kSwitchWidth = 59.0;
const double _kSwitchHeight = 39.0;
396 397
// Opacity of a disabled switch, as eye-balled from iOS Simulator on Mac.
const double _kCupertinoSwitchDisabledOpacity = 0.5;
398

399 400
const Duration _kReactionDuration = Duration(milliseconds: 300);
const Duration _kToggleDuration = Duration(milliseconds: 200);
401

402
class _RenderCupertinoSwitch extends RenderConstrainedBox {
403
  _RenderCupertinoSwitch({
404 405 406
    required bool value,
    required Color activeColor,
    required Color trackColor,
407
    required Color thumbColor,
408 409 410
    ValueChanged<bool>? onChanged,
    required TextDirection textDirection,
    required _CupertinoSwitchState state,
411 412
  }) : assert(value != null),
       assert(activeColor != null),
413
       assert(state != null),
414 415
       _value = value,
       _activeColor = activeColor,
416
       _trackColor = trackColor,
417
       _thumbPainter = CupertinoThumbPainter.switchThumb(color: thumbColor),
418
       _onChanged = onChanged,
419
       _textDirection = textDirection,
420
       _state = state,
421
       super(additionalConstraints: const BoxConstraints.tightFor(width: _kSwitchWidth, height: _kSwitchHeight)) {
422 423
         state.position.addListener(markNeedsPaint);
         state._reaction.addListener(markNeedsPaint);
424 425
  }

426
  final _CupertinoSwitchState _state;
427 428 429 430 431

  bool get value => _value;
  bool _value;
  set value(bool value) {
    assert(value != null);
432
    if (value == _value) {
433
      return;
434
    }
435
    _value = value;
436
    markNeedsSemanticsUpdate();
437 438 439 440 441 442
  }

  Color get activeColor => _activeColor;
  Color _activeColor;
  set activeColor(Color value) {
    assert(value != null);
443
    if (value == _activeColor) {
444
      return;
445
    }
446 447 448 449
    _activeColor = value;
    markNeedsPaint();
  }

450 451 452 453
  Color get trackColor => _trackColor;
  Color _trackColor;
  set trackColor(Color value) {
    assert(value != null);
454
    if (value == _trackColor) {
455
      return;
456
    }
457 458 459 460
    _trackColor = value;
    markNeedsPaint();
  }

461 462 463 464
  Color get thumbColor => _thumbPainter.color;
  CupertinoThumbPainter _thumbPainter;
  set thumbColor(Color value) {
    assert(value != null);
465
    if (value == thumbColor) {
466
      return;
467
    }
468 469 470 471
    _thumbPainter = CupertinoThumbPainter.switchThumb(color: value);
    markNeedsPaint();
  }

472 473 474
  ValueChanged<bool>? get onChanged => _onChanged;
  ValueChanged<bool>? _onChanged;
  set onChanged(ValueChanged<bool>? value) {
475
    if (value == _onChanged) {
476
      return;
477
    }
478 479 480 481
    final bool wasInteractive = isInteractive;
    _onChanged = value;
    if (wasInteractive != isInteractive) {
      markNeedsPaint();
482
      markNeedsSemanticsUpdate();
483 484 485
    }
  }

486 487 488 489
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    assert(value != null);
490
    if (_textDirection == value) {
491
      return;
492
    }
493 494 495 496
    _textDirection = value;
    markNeedsPaint();
  }

497 498 499
  bool get isInteractive => onChanged != null;

  @override
500
  bool hitTestSelf(Offset position) => true;
501 502 503 504 505

  @override
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
    assert(debugHandleEvent(event, entry));
    if (event is PointerDownEvent && isInteractive) {
506 507
      _state._drag.addPointer(event);
      _state._tap.addPointer(event);
508 509 510 511
    }
  }

  @override
512 513
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
514

515
    if (isInteractive) {
516
      config.onTap = _state._handleTap;
517
    }
518 519 520

    config.isEnabled = isInteractive;
    config.isToggled = _value;
521 522 523 524 525 526
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    final Canvas canvas = context.canvas;

527 528
    final double currentValue = _state.position.value;
    final double currentReactionValue = _state._reaction.value;
529

530
    final double visualPosition;
531 532 533 534 535 536 537 538 539
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - currentValue;
        break;
      case TextDirection.ltr:
        visualPosition = currentValue;
        break;
    }

540
    final Paint paint = Paint()
541
      ..color = Color.lerp(trackColor, activeColor, currentValue)!;
542

543
    final Rect trackRect = Rect.fromLTWH(
544 545 546
        offset.dx + (size.width - _kTrackWidth) / 2.0,
        offset.dy + (size.height - _kTrackHeight) / 2.0,
        _kTrackWidth,
547
        _kTrackHeight,
548
    );
549 550
    final RRect trackRRect = RRect.fromRectAndRadius(trackRect, const Radius.circular(_kTrackRadius));
    canvas.drawRRect(trackRRect, paint);
551

552
    final double currentThumbExtension = CupertinoThumbPainter.extension * currentReactionValue;
553
    final double thumbLeft = lerpDouble(
554 555
      trackRect.left + _kTrackInnerStart - CupertinoThumbPainter.radius,
      trackRect.left + _kTrackInnerEnd - CupertinoThumbPainter.radius - currentThumbExtension,
556
      visualPosition,
557
    )!;
558
    final double thumbRight = lerpDouble(
559 560
      trackRect.left + _kTrackInnerStart + CupertinoThumbPainter.radius + currentThumbExtension,
      trackRect.left + _kTrackInnerEnd + CupertinoThumbPainter.radius,
561
      visualPosition,
562
    )!;
563
    final double thumbCenterY = offset.dy + size.height / 2.0;
564
    final Rect thumbBounds = Rect.fromLTRB(
565 566 567 568
      thumbLeft,
      thumbCenterY - CupertinoThumbPainter.radius,
      thumbRight,
      thumbCenterY + CupertinoThumbPainter.radius,
569 570
    );

571
    _clipRRectLayer.layer = context.pushClipRRect(needsCompositing, Offset.zero, thumbBounds, trackRRect, (PaintingContext innerContext, Offset offset) {
572
      _thumbPainter.paint(innerContext.canvas, thumbBounds);
573
    }, oldLayer: _clipRRectLayer.layer);
574 575
  }

576 577 578 579 580 581 582
  final LayerHandle<ClipRRectLayer> _clipRRectLayer = LayerHandle<ClipRRectLayer>();

  @override
  void dispose() {
    _clipRRectLayer.layer = null;
    super.dispose();
  }
583

584
  @override
585
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
586
    super.debugFillProperties(description);
587 588
    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));
589 590
  }
}