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

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

  /// The color to use when this switch is on.
99
  ///
100
  /// Defaults to [CupertinoColors.systemGreen] when null and ignores
101
  /// the [CupertinoTheme] in accordance to native iOS behavior.
102
  final Color? activeColor;
103

104 105 106
  /// The color to use for the background when the switch is off.
  ///
  /// Defaults to [CupertinoColors.secondarySystemFill] when null.
107
  final Color? trackColor;
108

109 110 111 112 113
  /// The color to use for the thumb of the switch.
  ///
  /// Defaults to [CupertinoColors.white] when null.
  final Color? thumbColor;

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

136
  @override
137
  State<CupertinoSwitch> createState() => _CupertinoSwitchState();
138 139

  @override
140 141
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
142 143
    properties.add(FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true));
    properties.add(ObjectFlagProperty<ValueChanged<bool>>('onChanged', onChanged, ifNull: 'disabled'));
144 145 146 147
  }
}

class _CupertinoSwitchState extends State<CupertinoSwitch> with TickerProviderStateMixin {
148 149
  late TapGestureRecognizer _tap;
  late HorizontalDragGestureRecognizer _drag;
150

151 152
  late AnimationController _positionController;
  late CurvedAnimation position;
153

154 155
  late AnimationController _reactionController;
  late Animation<double> _reaction;
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

  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
215 216
      ..curve = isLinear ? Curves.linear : Curves.ease
      ..reverseCurve = isLinear ? Curves.linear : Curves.ease.flipped;
217 218 219 220 221 222 223 224 225 226 227 228 229 230
    if (widget.value)
      _positionController.forward();
    else
      _positionController.reverse();
  }

  void _handleTapDown(TapDownDetails details) {
    if (isInteractive)
      needsPositionAnimation = false;
      _reactionController.forward();
  }

  void _handleTap() {
    if (isInteractive) {
231
      widget.onChanged!(!widget.value);
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
      _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
259 260 261
        ..curve = Curves.linear
        ..reverseCurve = Curves.linear;
      final double delta = details.primaryDelta! / _kTrackInnerLength;
262
      switch (Directionality.of(context)) {
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
        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)
278
      widget.onChanged!(!widget.value);
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    _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;
    }
  }

296 297
  @override
  Widget build(BuildContext context) {
298 299
    if (needsPositionAnimation)
      _resumePositionAnimation();
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
    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,
315
        ),
316
      ),
317 318
    );
  }
319 320 321 322 323 324 325 326 327 328

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

    _positionController.dispose();
    _reactionController.dispose();
    super.dispose();
  }
329 330 331
}

class _CupertinoSwitchRenderObjectWidget extends LeafRenderObjectWidget {
332
  const _CupertinoSwitchRenderObjectWidget({
333 334 335
    required this.value,
    required this.activeColor,
    required this.trackColor,
336
    required this.thumbColor,
337 338 339
    required this.onChanged,
    required this.textDirection,
    required this.state,
340
  });
341 342 343

  final bool value;
  final Color activeColor;
344
  final Color trackColor;
345
  final Color thumbColor;
346
  final ValueChanged<bool>? onChanged;
347 348
  final _CupertinoSwitchState state;
  final TextDirection textDirection;
349 350 351

  @override
  _RenderCupertinoSwitch createRenderObject(BuildContext context) {
352
    return _RenderCupertinoSwitch(
353 354
      value: value,
      activeColor: activeColor,
355
      trackColor: trackColor,
356
      thumbColor: thumbColor,
357
      onChanged: onChanged,
358 359
      textDirection: textDirection,
      state: state,
360 361 362 363 364 365 366 367
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderCupertinoSwitch renderObject) {
    renderObject
      ..value = value
      ..activeColor = activeColor
368
      ..trackColor = trackColor
369
      ..thumbColor = thumbColor
370
      ..onChanged = onChanged
371
      ..textDirection = textDirection;
372 373 374
  }
}

375 376
const double _kTrackWidth = 51.0;
const double _kTrackHeight = 31.0;
377 378 379 380
const double _kTrackRadius = _kTrackHeight / 2.0;
const double _kTrackInnerStart = _kTrackHeight / 2.0;
const double _kTrackInnerEnd = _kTrackWidth - _kTrackInnerStart;
const double _kTrackInnerLength = _kTrackInnerEnd - _kTrackInnerStart;
381 382
const double _kSwitchWidth = 59.0;
const double _kSwitchHeight = 39.0;
383 384
// Opacity of a disabled switch, as eye-balled from iOS Simulator on Mac.
const double _kCupertinoSwitchDisabledOpacity = 0.5;
385

386 387
const Duration _kReactionDuration = Duration(milliseconds: 300);
const Duration _kToggleDuration = Duration(milliseconds: 200);
388

389
class _RenderCupertinoSwitch extends RenderConstrainedBox {
390
  _RenderCupertinoSwitch({
391 392 393
    required bool value,
    required Color activeColor,
    required Color trackColor,
394
    required Color thumbColor,
395 396 397
    ValueChanged<bool>? onChanged,
    required TextDirection textDirection,
    required _CupertinoSwitchState state,
398 399
  }) : assert(value != null),
       assert(activeColor != null),
400
       assert(state != null),
401 402
       _value = value,
       _activeColor = activeColor,
403
       _trackColor = trackColor,
404
       _thumbPainter = CupertinoThumbPainter.switchThumb(color: thumbColor),
405
       _onChanged = onChanged,
406
       _textDirection = textDirection,
407
       _state = state,
408
       super(additionalConstraints: const BoxConstraints.tightFor(width: _kSwitchWidth, height: _kSwitchHeight)) {
409 410
         state.position.addListener(markNeedsPaint);
         state._reaction.addListener(markNeedsPaint);
411 412
  }

413
  final _CupertinoSwitchState _state;
414 415 416 417 418 419 420 421

  bool get value => _value;
  bool _value;
  set value(bool value) {
    assert(value != null);
    if (value == _value)
      return;
    _value = value;
422
    markNeedsSemanticsUpdate();
423 424 425 426 427 428 429 430 431 432 433 434
  }

  Color get activeColor => _activeColor;
  Color _activeColor;
  set activeColor(Color value) {
    assert(value != null);
    if (value == _activeColor)
      return;
    _activeColor = value;
    markNeedsPaint();
  }

435 436 437 438 439 440 441 442 443 444
  Color get trackColor => _trackColor;
  Color _trackColor;
  set trackColor(Color value) {
    assert(value != null);
    if (value == _trackColor)
      return;
    _trackColor = value;
    markNeedsPaint();
  }

445 446 447 448 449 450 451 452 453 454
  Color get thumbColor => _thumbPainter.color;
  CupertinoThumbPainter _thumbPainter;
  set thumbColor(Color value) {
    assert(value != null);
    if (value == thumbColor)
      return;
    _thumbPainter = CupertinoThumbPainter.switchThumb(color: value);
    markNeedsPaint();
  }

455 456 457
  ValueChanged<bool>? get onChanged => _onChanged;
  ValueChanged<bool>? _onChanged;
  set onChanged(ValueChanged<bool>? value) {
458 459 460 461 462 463
    if (value == _onChanged)
      return;
    final bool wasInteractive = isInteractive;
    _onChanged = value;
    if (wasInteractive != isInteractive) {
      markNeedsPaint();
464
      markNeedsSemanticsUpdate();
465 466 467
    }
  }

468 469 470 471 472 473 474 475 476 477
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    assert(value != null);
    if (_textDirection == value)
      return;
    _textDirection = value;
    markNeedsPaint();
  }

478 479 480
  bool get isInteractive => onChanged != null;

  @override
481
  bool hitTestSelf(Offset position) => true;
482 483 484 485 486

  @override
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
    assert(debugHandleEvent(event, entry));
    if (event is PointerDownEvent && isInteractive) {
487 488
      _state._drag.addPointer(event);
      _state._tap.addPointer(event);
489 490 491 492
    }
  }

  @override
493 494
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
495 496

    if (isInteractive)
497
      config.onTap = _state._handleTap;
498 499 500

    config.isEnabled = isInteractive;
    config.isToggled = _value;
501 502 503 504 505 506
  }

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

507 508
    final double currentValue = _state.position.value;
    final double currentReactionValue = _state._reaction.value;
509

510
    final double visualPosition;
511 512 513 514 515 516 517 518 519
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - currentValue;
        break;
      case TextDirection.ltr:
        visualPosition = currentValue;
        break;
    }

520
    final Paint paint = Paint()
521
      ..color = Color.lerp(trackColor, activeColor, currentValue)!;
522

523
    final Rect trackRect = Rect.fromLTWH(
524 525 526
        offset.dx + (size.width - _kTrackWidth) / 2.0,
        offset.dy + (size.height - _kTrackHeight) / 2.0,
        _kTrackWidth,
527
        _kTrackHeight,
528
    );
529 530
    final RRect trackRRect = RRect.fromRectAndRadius(trackRect, const Radius.circular(_kTrackRadius));
    canvas.drawRRect(trackRRect, paint);
531

532
    final double currentThumbExtension = CupertinoThumbPainter.extension * currentReactionValue;
533
    final double thumbLeft = lerpDouble(
534 535
      trackRect.left + _kTrackInnerStart - CupertinoThumbPainter.radius,
      trackRect.left + _kTrackInnerEnd - CupertinoThumbPainter.radius - currentThumbExtension,
536
      visualPosition,
537
    )!;
538
    final double thumbRight = lerpDouble(
539 540
      trackRect.left + _kTrackInnerStart + CupertinoThumbPainter.radius + currentThumbExtension,
      trackRect.left + _kTrackInnerEnd + CupertinoThumbPainter.radius,
541
      visualPosition,
542
    )!;
543
    final double thumbCenterY = offset.dy + size.height / 2.0;
544
    final Rect thumbBounds = Rect.fromLTRB(
545 546 547 548
      thumbLeft,
      thumbCenterY - CupertinoThumbPainter.radius,
      thumbRight,
      thumbCenterY + CupertinoThumbPainter.radius,
549 550
    );

551
    _clipRRectLayer.layer = context.pushClipRRect(needsCompositing, Offset.zero, thumbBounds, trackRRect, (PaintingContext innerContext, Offset offset) {
552
      _thumbPainter.paint(innerContext.canvas, thumbBounds);
553
    }, oldLayer: _clipRRectLayer.layer);
554 555
  }

556 557 558 559 560 561 562
  final LayerHandle<ClipRRectLayer> _clipRRectLayer = LayerHandle<ClipRRectLayer>();

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

564
  @override
565
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
566
    super.debugFillProperties(description);
567 568
    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));
569 570
  }
}