switch.dart 15.9 KB
Newer Older
1 2 3 4 5 6
// Copyright 2017 The Chromium Authors. All rights reserved.
// 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 10
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
11
import 'package:flutter/services.dart';
12

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

16 17 18 19
// Examples can assume:
// bool _lights;
// 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 sample}
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 38 39
/// MergeSemantics(
///   child: ListTile(
///     title: Text('Lights'),
///     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.dragStartBehavior = DragStartBehavior.start,
64 65
  }) : assert(value != null),
       assert(dragStartBehavior != null),
66
       super(key: key);
67 68

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

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

103 104 105 106 107 108 109 110 111 112 113 114
  /// {@template flutter.cupertino.switch.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 upon the detection of a drag gesture. If
  /// set to [DragStartBehavior.down] it will begin when a down event is 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.
  ///
115
  /// By default, the drag start behavior is [DragStartBehavior.start].
116 117 118
  ///
  /// See also:
  ///
119 120 121
  ///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for
  ///    the different behaviors.
  ///
122 123 124
  /// {@endtemplate}
  final DragStartBehavior dragStartBehavior;

125
  @override
126
  _CupertinoSwitchState createState() => _CupertinoSwitchState();
127 128

  @override
129 130
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
131 132
    properties.add(FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true));
    properties.add(ObjectFlagProperty<ValueChanged<bool>>('onChanged', onChanged, ifNull: 'disabled'));
133 134 135 136 137 138
  }
}

class _CupertinoSwitchState extends State<CupertinoSwitch> with TickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
139 140 141 142
    return Opacity(
      opacity: widget.onChanged == null ? _kCupertinoSwitchDisabledOpacity : 1.0,
      child: _CupertinoSwitchRenderObjectWidget(
        value: widget.value,
143
        activeColor: CupertinoDynamicColor.resolve(
144
          widget.activeColor ?? CupertinoColors.systemGreen,
145 146
          context,
        ),
147 148 149 150
        onChanged: widget.onChanged,
        vsync: this,
        dragStartBehavior: widget.dragStartBehavior,
      ),
151 152 153 154 155
    );
  }
}

class _CupertinoSwitchRenderObjectWidget extends LeafRenderObjectWidget {
156
  const _CupertinoSwitchRenderObjectWidget({
157 158 159 160 161
    Key key,
    this.value,
    this.activeColor,
    this.onChanged,
    this.vsync,
162
    this.dragStartBehavior = DragStartBehavior.start,
163 164 165 166 167 168
  }) : super(key: key);

  final bool value;
  final Color activeColor;
  final ValueChanged<bool> onChanged;
  final TickerProvider vsync;
169
  final DragStartBehavior dragStartBehavior;
170 171 172

  @override
  _RenderCupertinoSwitch createRenderObject(BuildContext context) {
173
    return _RenderCupertinoSwitch(
174 175
      value: value,
      activeColor: activeColor,
176
      trackColor: CupertinoDynamicColor.resolve(CupertinoColors.secondarySystemFill, context),
177
      onChanged: onChanged,
178
      textDirection: Directionality.of(context),
179
      vsync: vsync,
180
      dragStartBehavior: dragStartBehavior,
181 182 183 184 185 186 187 188
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderCupertinoSwitch renderObject) {
    renderObject
      ..value = value
      ..activeColor = activeColor
189
      ..trackColor = CupertinoDynamicColor.resolve(CupertinoColors.secondarySystemFill, context)
190
      ..onChanged = onChanged
191
      ..textDirection = Directionality.of(context)
192 193
      ..vsync = vsync
      ..dragStartBehavior = dragStartBehavior;
194 195 196
  }
}

197 198
const double _kTrackWidth = 51.0;
const double _kTrackHeight = 31.0;
199 200 201 202
const double _kTrackRadius = _kTrackHeight / 2.0;
const double _kTrackInnerStart = _kTrackHeight / 2.0;
const double _kTrackInnerEnd = _kTrackWidth - _kTrackInnerStart;
const double _kTrackInnerLength = _kTrackInnerEnd - _kTrackInnerStart;
203 204
const double _kSwitchWidth = 59.0;
const double _kSwitchHeight = 39.0;
205 206
// Opacity of a disabled switch, as eye-balled from iOS Simulator on Mac.
const double _kCupertinoSwitchDisabledOpacity = 0.5;
207

208 209
const Duration _kReactionDuration = Duration(milliseconds: 300);
const Duration _kToggleDuration = Duration(milliseconds: 200);
210

211
class _RenderCupertinoSwitch extends RenderConstrainedBox {
212
  _RenderCupertinoSwitch({
213 214
    @required bool value,
    @required Color activeColor,
215
    @required Color trackColor,
216
    ValueChanged<bool> onChanged,
217
    @required TextDirection textDirection,
218
    @required TickerProvider vsync,
219
    DragStartBehavior dragStartBehavior = DragStartBehavior.start,
220 221 222 223 224
  }) : assert(value != null),
       assert(activeColor != null),
       assert(vsync != null),
       _value = value,
       _activeColor = activeColor,
225
       _trackColor = trackColor,
226
       _onChanged = onChanged,
227
       _textDirection = textDirection,
228 229
       _vsync = vsync,
       super(additionalConstraints: const BoxConstraints.tightFor(width: _kSwitchWidth, height: _kSwitchHeight)) {
230
    _tap = TapGestureRecognizer()
231 232 233 234
      ..onTapDown = _handleTapDown
      ..onTap = _handleTap
      ..onTapUp = _handleTapUp
      ..onTapCancel = _handleTapCancel;
235
    _drag = HorizontalDragGestureRecognizer()
236 237
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
238 239
      ..onEnd = _handleDragEnd
      ..dragStartBehavior = dragStartBehavior;
240
    _positionController = AnimationController(
241 242 243 244
      duration: _kToggleDuration,
      value: value ? 1.0 : 0.0,
      vsync: vsync,
    );
245
    _position = CurvedAnimation(
246 247 248 249
      parent: _positionController,
      curve: Curves.linear,
    )..addListener(markNeedsPaint)
     ..addStatusListener(_handlePositionStateChanged);
250
    _reactionController = AnimationController(
251 252 253
      duration: _kReactionDuration,
      vsync: vsync,
    );
254
    _reaction = CurvedAnimation(
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
      parent: _reactionController,
      curve: Curves.ease,
    )..addListener(markNeedsPaint);
  }

  AnimationController _positionController;
  CurvedAnimation _position;

  AnimationController _reactionController;
  Animation<double> _reaction;

  bool get value => _value;
  bool _value;
  set value(bool value) {
    assert(value != null);
    if (value == _value)
      return;
    _value = value;
273
    markNeedsSemanticsUpdate();
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
    _position
      ..curve = Curves.ease
      ..reverseCurve = Curves.ease.flipped;
    if (value)
      _positionController.forward();
    else
      _positionController.reverse();
  }

  TickerProvider get vsync => _vsync;
  TickerProvider _vsync;
  set vsync(TickerProvider value) {
    assert(value != null);
    if (value == _vsync)
      return;
    _vsync = value;
    _positionController.resync(vsync);
    _reactionController.resync(vsync);
  }

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

304 305 306 307 308 309 310 311 312 313
  Color get trackColor => _trackColor;
  Color _trackColor;
  set trackColor(Color value) {
    assert(value != null);
    if (value == _trackColor)
      return;
    _trackColor = value;
    markNeedsPaint();
  }

314 315 316 317 318 319 320 321 322
  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();
323
      markNeedsSemanticsUpdate();
324 325 326
    }
  }

327 328 329 330 331 332 333 334 335 336
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    assert(value != null);
    if (_textDirection == value)
      return;
    _textDirection = value;
    markNeedsPaint();
  }

337 338 339 340 341 342 343 344
  DragStartBehavior get dragStartBehavior => _drag.dragStartBehavior;
  set dragStartBehavior(DragStartBehavior value) {
    assert(value != null);
    if (_drag.dragStartBehavior == value)
      return;
    _drag.dragStartBehavior = value;
  }

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
  bool get isInteractive => onChanged != null;

  TapGestureRecognizer _tap;
  HorizontalDragGestureRecognizer _drag;

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    if (value)
      _positionController.forward();
    else
      _positionController.reverse();
    if (isInteractive) {
      switch (_reactionController.status) {
        case AnimationStatus.forward:
          _reactionController.forward();
          break;
        case AnimationStatus.reverse:
          _reactionController.reverse();
          break;
        case AnimationStatus.dismissed:
        case AnimationStatus.completed:
          // nothing to do
          break;
      }
    }
  }

  @override
  void detach() {
    _positionController.stop();
    _reactionController.stop();
    super.detach();
  }

  void _handlePositionStateChanged(AnimationStatus status) {
    if (isInteractive) {
      if (status == AnimationStatus.completed && !_value)
        onChanged(true);
      else if (status == AnimationStatus.dismissed && _value)
        onChanged(false);
    }
  }

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

  void _handleTap() {
395
    if (isInteractive) {
396
      onChanged(!_value);
397 398
      _emitVibration();
    }
399 400 401 402 403 404 405 406 407 408 409 410 411
  }

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

  void _handleTapCancel() {
    if (isInteractive)
      _reactionController.reverse();
  }

  void _handleDragStart(DragStartDetails details) {
412
    if (isInteractive) {
413
      _reactionController.forward();
414 415
      _emitVibration();
    }
416 417 418 419 420 421 422
  }

  void _handleDragUpdate(DragUpdateDetails details) {
    if (isInteractive) {
      _position
        ..curve = null
        ..reverseCurve = null;
423 424 425 426 427 428 429 430 431
      final double delta = details.primaryDelta / _kTrackInnerLength;
      switch (textDirection) {
        case TextDirection.rtl:
          _positionController.value -= delta;
          break;
        case TextDirection.ltr:
          _positionController.value += delta;
          break;
      }
432 433 434 435 436 437 438 439 440 441 442
    }
  }

  void _handleDragEnd(DragEndDetails details) {
    if (_position.value >= 0.5)
      _positionController.forward();
    else
      _positionController.reverse();
    _reactionController.reverse();
  }

443
  void _emitVibration() {
444
    switch (defaultTargetPlatform) {
445 446 447 448 449 450 451 452 453
      case TargetPlatform.iOS:
        HapticFeedback.lightImpact();
        break;
      case TargetPlatform.fuchsia:
      case TargetPlatform.android:
        break;
    }
  }

454
  @override
455
  bool hitTestSelf(Offset position) => true;
456 457 458 459 460 461 462 463 464 465 466

  @override
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
    assert(debugHandleEvent(event, entry));
    if (event is PointerDownEvent && isInteractive) {
      _drag.addPointer(event);
      _tap.addPointer(event);
    }
  }

  @override
467 468
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
469 470

    if (isInteractive)
471
      config.onTap = _handleTap;
472 473 474

    config.isEnabled = isInteractive;
    config.isToggled = _value;
475 476 477 478 479 480
  }

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

481
    final double currentValue = _position.value;
482 483
    final double currentReactionValue = _reaction.value;

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

494
    final Paint paint = Paint()
495
      ..color = Color.lerp(trackColor, activeColor, currentValue);
496

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

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

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

  @override
531
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
532
    super.debugFillProperties(description);
533 534
    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));
535 536
  }
}