switch.dart 17.4 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.thumbColor,
65
    this.dragStartBehavior = DragStartBehavior.start,
66 67
  }) : assert(value != null),
       assert(dragStartBehavior != null),
68
       super(key: key);
69 70

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

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

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

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

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

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

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

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

152 153
  late AnimationController _positionController;
  late CurvedAnimation position;
154

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

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

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

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

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

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

    _positionController.dispose();
    _reactionController.dispose();
    super.dispose();
  }
327 328 329
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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