switch.dart 16.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 60 61
    Key? key,
    required this.value,
    required this.onChanged,
62
    this.activeColor,
63
    this.trackColor,
64
    this.dragStartBehavior = DragStartBehavior.start,
65 66
  }) : assert(value != null),
       assert(dragStartBehavior != null),
67
       super(key: key);
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
  /// {@template flutter.cupertino.CupertinoSwitch.dragStartBehavior}
110 111 112
  /// Determines the way that drag start behavior is handled.
  ///
  /// If set to [DragStartBehavior.start], the drag behavior used to move the
113 114 115
  /// 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.
116 117 118 119 120
  ///
  /// 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.
  ///
121
  /// By default, the drag start behavior is [DragStartBehavior.start].
122 123 124
  ///
  /// See also:
  ///
125 126 127
  ///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for
  ///    the different behaviors.
  ///
128 129 130
  /// {@endtemplate}
  final DragStartBehavior dragStartBehavior;

131
  @override
132
  State<CupertinoSwitch> createState() => _CupertinoSwitchState();
133 134

  @override
135 136
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
137 138
    properties.add(FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true));
    properties.add(ObjectFlagProperty<ValueChanged<bool>>('onChanged', onChanged, ifNull: 'disabled'));
139 140 141 142
  }
}

class _CupertinoSwitchState extends State<CupertinoSwitch> with TickerProviderStateMixin {
143 144
  late TapGestureRecognizer _tap;
  late HorizontalDragGestureRecognizer _drag;
145

146 147
  late AnimationController _positionController;
  late CurvedAnimation position;
148

149 150
  late AnimationController _reactionController;
  late Animation<double> _reaction;
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

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

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

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

291 292
  @override
  Widget build(BuildContext context) {
293 294
    if (needsPositionAnimation)
      _resumePositionAnimation();
295 296 297 298
    return Opacity(
      opacity: widget.onChanged == null ? _kCupertinoSwitchDisabledOpacity : 1.0,
      child: _CupertinoSwitchRenderObjectWidget(
        value: widget.value,
299
        activeColor: CupertinoDynamicColor.resolve(
300
          widget.activeColor ?? CupertinoColors.systemGreen,
301
          context,
302 303
        ),
        trackColor: CupertinoDynamicColor.resolve(widget.trackColor ?? CupertinoColors.secondarySystemFill, context),
304
        onChanged: widget.onChanged,
305
        textDirection: Directionality.of(context),
306
        state: this,
307
      ),
308 309
    );
  }
310 311 312 313 314 315 316 317 318 319

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

    _positionController.dispose();
    _reactionController.dispose();
    super.dispose();
  }
320 321 322
}

class _CupertinoSwitchRenderObjectWidget extends LeafRenderObjectWidget {
323
  const _CupertinoSwitchRenderObjectWidget({
324 325 326 327 328 329 330
    Key? key,
    required this.value,
    required this.activeColor,
    required this.trackColor,
    required this.onChanged,
    required this.textDirection,
    required this.state,
331 332 333 334
  }) : super(key: key);

  final bool value;
  final Color activeColor;
335
  final Color trackColor;
336
  final ValueChanged<bool>? onChanged;
337 338
  final _CupertinoSwitchState state;
  final TextDirection textDirection;
339 340 341

  @override
  _RenderCupertinoSwitch createRenderObject(BuildContext context) {
342
    return _RenderCupertinoSwitch(
343 344
      value: value,
      activeColor: activeColor,
345
      trackColor: trackColor,
346
      onChanged: onChanged,
347 348
      textDirection: textDirection,
      state: state,
349 350 351 352 353 354 355 356
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderCupertinoSwitch renderObject) {
    renderObject
      ..value = value
      ..activeColor = activeColor
357
      ..trackColor = trackColor
358
      ..onChanged = onChanged
359
      ..textDirection = textDirection;
360 361 362
  }
}

363 364
const double _kTrackWidth = 51.0;
const double _kTrackHeight = 31.0;
365 366 367 368
const double _kTrackRadius = _kTrackHeight / 2.0;
const double _kTrackInnerStart = _kTrackHeight / 2.0;
const double _kTrackInnerEnd = _kTrackWidth - _kTrackInnerStart;
const double _kTrackInnerLength = _kTrackInnerEnd - _kTrackInnerStart;
369 370
const double _kSwitchWidth = 59.0;
const double _kSwitchHeight = 39.0;
371 372
// Opacity of a disabled switch, as eye-balled from iOS Simulator on Mac.
const double _kCupertinoSwitchDisabledOpacity = 0.5;
373

374 375
const Duration _kReactionDuration = Duration(milliseconds: 300);
const Duration _kToggleDuration = Duration(milliseconds: 200);
376

377
class _RenderCupertinoSwitch extends RenderConstrainedBox {
378
  _RenderCupertinoSwitch({
379 380 381 382 383 384
    required bool value,
    required Color activeColor,
    required Color trackColor,
    ValueChanged<bool>? onChanged,
    required TextDirection textDirection,
    required _CupertinoSwitchState state,
385 386
  }) : assert(value != null),
       assert(activeColor != null),
387
       assert(state != null),
388 389
       _value = value,
       _activeColor = activeColor,
390
       _trackColor = trackColor,
391
       _onChanged = onChanged,
392
       _textDirection = textDirection,
393
       _state = state,
394
       super(additionalConstraints: const BoxConstraints.tightFor(width: _kSwitchWidth, height: _kSwitchHeight)) {
395 396
         state.position.addListener(markNeedsPaint);
         state._reaction.addListener(markNeedsPaint);
397 398
  }

399
  final _CupertinoSwitchState _state;
400 401 402 403 404 405 406 407

  bool get value => _value;
  bool _value;
  set value(bool value) {
    assert(value != null);
    if (value == _value)
      return;
    _value = value;
408
    markNeedsSemanticsUpdate();
409 410 411 412 413 414 415 416 417 418 419 420
  }

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

421 422 423 424 425 426 427 428 429 430
  Color get trackColor => _trackColor;
  Color _trackColor;
  set trackColor(Color value) {
    assert(value != null);
    if (value == _trackColor)
      return;
    _trackColor = value;
    markNeedsPaint();
  }

431 432 433
  ValueChanged<bool>? get onChanged => _onChanged;
  ValueChanged<bool>? _onChanged;
  set onChanged(ValueChanged<bool>? value) {
434 435 436 437 438 439
    if (value == _onChanged)
      return;
    final bool wasInteractive = isInteractive;
    _onChanged = value;
    if (wasInteractive != isInteractive) {
      markNeedsPaint();
440
      markNeedsSemanticsUpdate();
441 442 443
    }
  }

444 445 446 447 448 449 450 451 452 453
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    assert(value != null);
    if (_textDirection == value)
      return;
    _textDirection = value;
    markNeedsPaint();
  }

454 455 456
  bool get isInteractive => onChanged != null;

  @override
457
  bool hitTestSelf(Offset position) => true;
458 459 460 461 462

  @override
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
    assert(debugHandleEvent(event, entry));
    if (event is PointerDownEvent && isInteractive) {
463 464
      _state._drag.addPointer(event);
      _state._tap.addPointer(event);
465 466 467 468
    }
  }

  @override
469 470
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
471 472

    if (isInteractive)
473
      config.onTap = _state._handleTap;
474 475 476

    config.isEnabled = isInteractive;
    config.isToggled = _value;
477 478 479 480 481 482
  }

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

483 484
    final double currentValue = _state.position.value;
    final double currentReactionValue = _state._reaction.value;
485

486
    final double visualPosition;
487 488 489 490 491 492 493 494 495
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - currentValue;
        break;
      case TextDirection.ltr:
        visualPosition = currentValue;
        break;
    }

496
    final Paint paint = Paint()
497
      ..color = Color.lerp(trackColor, activeColor, currentValue)!;
498

499
    final Rect trackRect = Rect.fromLTWH(
500 501 502
        offset.dx + (size.width - _kTrackWidth) / 2.0,
        offset.dy + (size.height - _kTrackHeight) / 2.0,
        _kTrackWidth,
503
        _kTrackHeight,
504
    );
505 506
    final RRect trackRRect = RRect.fromRectAndRadius(trackRect, const Radius.circular(_kTrackRadius));
    canvas.drawRRect(trackRRect, paint);
507

508
    final double currentThumbExtension = CupertinoThumbPainter.extension * currentReactionValue;
509
    final double thumbLeft = lerpDouble(
510 511
      trackRect.left + _kTrackInnerStart - CupertinoThumbPainter.radius,
      trackRect.left + _kTrackInnerEnd - CupertinoThumbPainter.radius - currentThumbExtension,
512
      visualPosition,
513
    )!;
514
    final double thumbRight = lerpDouble(
515 516
      trackRect.left + _kTrackInnerStart + CupertinoThumbPainter.radius + currentThumbExtension,
      trackRect.left + _kTrackInnerEnd + CupertinoThumbPainter.radius,
517
      visualPosition,
518
    )!;
519
    final double thumbCenterY = offset.dy + size.height / 2.0;
520
    final Rect thumbBounds = Rect.fromLTRB(
521 522 523 524
      thumbLeft,
      thumbCenterY - CupertinoThumbPainter.radius,
      thumbRight,
      thumbCenterY + CupertinoThumbPainter.radius,
525 526
    );

527
    _clipRRectLayer = context.pushClipRRect(needsCompositing, Offset.zero, thumbBounds, trackRRect, (PaintingContext innerContext, Offset offset) {
528
      const CupertinoThumbPainter.switchThumb().paint(innerContext.canvas, thumbBounds);
529
    }, oldLayer: _clipRRectLayer);
530 531
  }

532 533
  ClipRRectLayer? _clipRRectLayer;

534
  @override
535
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
536
    super.debugFillProperties(description);
537 538
    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));
539 540
  }
}