switch.dart 15.2 KB
Newer Older
1 2 3 4 5 6 7
// 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:math' as math;
import 'dart:ui' show lerpDouble;

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

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

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

21 22 23 24 25 26 27 28 29
/// 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.
///
30
/// {@tool sample}
31 32 33 34 35 36
///
/// 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
37 38 39 40
/// MergeSemantics(
///   child: ListTile(
///     title: Text('Lights'),
///     trailing: CupertinoSwitch(
41 42 43 44 45 46 47
///       value: _lights,
///       onChanged: (bool value) { setState(() { _lights = value; }); },
///     ),
///     onTap: () { setState(() { _lights = !_lights; }); },
///   ),
/// )
/// ```
48
/// {@end-tool}
49
///
50 51
/// See also:
///
52
///  * [Switch], the material design equivalent.
53
///  * <https://developer.apple.com/ios/human-interface-guidelines/controls/switches/>
54
class CupertinoSwitch extends StatefulWidget {
Adam Barth's avatar
Adam Barth committed
55
  /// Creates an iOS-style switch.
56 57
  ///
  /// [dragStartBehavior] 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(dragStartBehavior != null),
       super(key: key);
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

  /// Whether this switch is on or off.
  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.
  ///
  /// If null, the switch will be displayed as disabled.
  ///
  /// 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
83
  /// CupertinoSwitch(
84 85 86 87 88 89
  ///   value: _giveVerse,
  ///   onChanged: (bool newValue) {
  ///     setState(() {
  ///       _giveVerse = newValue;
  ///     });
  ///   },
90
  /// )
91 92 93 94
  /// ```
  final ValueChanged<bool> onChanged;

  /// The color to use when this switch is on.
95
  ///
xster's avatar
xster committed
96 97
  /// Defaults to [CupertinoColors.activeGreen] when null and ignores the
  /// [CupertinoTheme] in accordance to native iOS behavior.
98 99
  final Color activeColor;

100 101 102 103 104 105 106 107 108 109 110 111
  /// {@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.
  ///
112
  /// By default, the drag start behavior is [DragStartBehavior.start].
113 114 115 116 117 118 119
  ///
  /// See also:
  ///
  ///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for the different behaviors.
  /// {@endtemplate}
  final DragStartBehavior dragStartBehavior;

120
  @override
121
  _CupertinoSwitchState createState() => _CupertinoSwitchState();
122 123

  @override
124 125
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
126 127
    properties.add(FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true));
    properties.add(ObjectFlagProperty<ValueChanged<bool>>('onChanged', onChanged, ifNull: 'disabled'));
128 129 130 131 132 133
  }
}

class _CupertinoSwitchState extends State<CupertinoSwitch> with TickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
134
    return _CupertinoSwitchRenderObjectWidget(
135
      value: widget.value,
136
      activeColor: widget.activeColor ?? CupertinoColors.activeGreen,
137
      onChanged: widget.onChanged,
138
      vsync: this,
139
      dragStartBehavior: widget.dragStartBehavior,
140 141 142 143 144
    );
  }
}

class _CupertinoSwitchRenderObjectWidget extends LeafRenderObjectWidget {
145
  const _CupertinoSwitchRenderObjectWidget({
146 147 148 149 150
    Key key,
    this.value,
    this.activeColor,
    this.onChanged,
    this.vsync,
151
    this.dragStartBehavior = DragStartBehavior.start,
152 153 154 155 156 157
  }) : super(key: key);

  final bool value;
  final Color activeColor;
  final ValueChanged<bool> onChanged;
  final TickerProvider vsync;
158
  final DragStartBehavior dragStartBehavior;
159 160 161

  @override
  _RenderCupertinoSwitch createRenderObject(BuildContext context) {
162
    return _RenderCupertinoSwitch(
163 164 165
      value: value,
      activeColor: activeColor,
      onChanged: onChanged,
166
      textDirection: Directionality.of(context),
167
      vsync: vsync,
168
      dragStartBehavior: dragStartBehavior,
169 170 171 172 173 174 175 176 177
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderCupertinoSwitch renderObject) {
    renderObject
      ..value = value
      ..activeColor = activeColor
      ..onChanged = onChanged
178
      ..textDirection = Directionality.of(context)
179 180
      ..vsync = vsync
      ..dragStartBehavior = dragStartBehavior;
181 182 183
  }
}

184 185
const double _kTrackWidth = 51.0;
const double _kTrackHeight = 31.0;
186 187 188 189
const double _kTrackRadius = _kTrackHeight / 2.0;
const double _kTrackInnerStart = _kTrackHeight / 2.0;
const double _kTrackInnerEnd = _kTrackWidth - _kTrackInnerStart;
const double _kTrackInnerLength = _kTrackInnerEnd - _kTrackInnerStart;
190 191
const double _kSwitchWidth = 59.0;
const double _kSwitchHeight = 39.0;
192

xster's avatar
xster committed
193
const Color _kTrackColor = CupertinoColors.lightBackgroundGray;
194 195
const Duration _kReactionDuration = Duration(milliseconds: 300);
const Duration _kToggleDuration = Duration(milliseconds: 200);
196

197
class _RenderCupertinoSwitch extends RenderConstrainedBox {
198
  _RenderCupertinoSwitch({
199 200
    @required bool value,
    @required Color activeColor,
201
    ValueChanged<bool> onChanged,
202
    @required TextDirection textDirection,
203
    @required TickerProvider vsync,
204
    DragStartBehavior dragStartBehavior = DragStartBehavior.start,
205 206 207 208 209 210
  }) : assert(value != null),
       assert(activeColor != null),
       assert(vsync != null),
       _value = value,
       _activeColor = activeColor,
       _onChanged = onChanged,
211
       _textDirection = textDirection,
212 213
       _vsync = vsync,
       super(additionalConstraints: const BoxConstraints.tightFor(width: _kSwitchWidth, height: _kSwitchHeight)) {
214
    _tap = TapGestureRecognizer()
215 216 217 218
      ..onTapDown = _handleTapDown
      ..onTap = _handleTap
      ..onTapUp = _handleTapUp
      ..onTapCancel = _handleTapCancel;
219
    _drag = HorizontalDragGestureRecognizer()
220 221
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
222 223
      ..onEnd = _handleDragEnd
      ..dragStartBehavior = dragStartBehavior;
224
    _positionController = AnimationController(
225 226 227 228
      duration: _kToggleDuration,
      value: value ? 1.0 : 0.0,
      vsync: vsync,
    );
229
    _position = CurvedAnimation(
230 231 232 233
      parent: _positionController,
      curve: Curves.linear,
    )..addListener(markNeedsPaint)
     ..addStatusListener(_handlePositionStateChanged);
234
    _reactionController = AnimationController(
235 236 237
      duration: _kReactionDuration,
      vsync: vsync,
    );
238
    _reaction = CurvedAnimation(
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
      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;
257
    markNeedsSemanticsUpdate();
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    _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();
  }

  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();
297
      markNeedsSemanticsUpdate();
298 299 300
    }
  }

301 302 303 304 305 306 307 308 309 310
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    assert(value != null);
    if (_textDirection == value)
      return;
    _textDirection = value;
    markNeedsPaint();
  }

311 312 313 314 315 316 317 318
  DragStartBehavior get dragStartBehavior => _drag.dragStartBehavior;
  set dragStartBehavior(DragStartBehavior value) {
    assert(value != null);
    if (_drag.dragStartBehavior == value)
      return;
    _drag.dragStartBehavior = value;
  }

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
  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() {
369
    if (isInteractive) {
370
      onChanged(!_value);
371 372
      _emitVibration();
    }
373 374 375 376 377 378 379 380 381 382 383 384 385
  }

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

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

  void _handleDragStart(DragStartDetails details) {
386
    if (isInteractive) {
387
      _reactionController.forward();
388 389
      _emitVibration();
    }
390 391 392 393 394 395 396
  }

  void _handleDragUpdate(DragUpdateDetails details) {
    if (isInteractive) {
      _position
        ..curve = null
        ..reverseCurve = null;
397 398 399 400 401 402 403 404 405
      final double delta = details.primaryDelta / _kTrackInnerLength;
      switch (textDirection) {
        case TextDirection.rtl:
          _positionController.value -= delta;
          break;
        case TextDirection.ltr:
          _positionController.value += delta;
          break;
      }
406 407 408 409 410 411 412 413 414 415 416
    }
  }

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

417
  void _emitVibration() {
418 419 420 421 422 423 424 425 426 427
    switch(defaultTargetPlatform) {
      case TargetPlatform.iOS:
        HapticFeedback.lightImpact();
        break;
      case TargetPlatform.fuchsia:
      case TargetPlatform.android:
        break;
    }
  }

428
  @override
429
  bool hitTestSelf(Offset position) => true;
430 431 432 433 434 435 436 437 438 439 440

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

  @override
441 442
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
443 444

    if (isInteractive)
445
      config.onTap = _handleTap;
446 447 448

    config.isEnabled = isInteractive;
    config.isToggled = _value;
449 450
  }

451
  final CupertinoThumbPainter _thumbPainter = CupertinoThumbPainter();
452

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

457
    final double currentValue = _position.value;
458 459
    final double currentReactionValue = _reaction.value;

460 461 462 463 464 465 466 467 468 469
    double visualPosition;
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - currentValue;
        break;
      case TextDirection.ltr:
        visualPosition = currentValue;
        break;
    }

470
    final Color trackColor = _value ? activeColor : _kTrackColor;
471
    final double borderThickness = 1.5 + (_kTrackRadius - 1.5) * math.max(currentReactionValue, currentValue);
472

473
    final Paint paint = Paint()
474 475
      ..color = trackColor;

476
    final Rect trackRect = Rect.fromLTWH(
477 478 479
        offset.dx + (size.width - _kTrackWidth) / 2.0,
        offset.dy + (size.height - _kTrackHeight) / 2.0,
        _kTrackWidth,
480
        _kTrackHeight,
481
    );
482 483
    final RRect outerRRect = RRect.fromRectAndRadius(trackRect, const Radius.circular(_kTrackRadius));
    final RRect innerRRect = RRect.fromRectAndRadius(trackRect.deflate(borderThickness), const Radius.circular(_kTrackRadius));
484 485
    canvas.drawDRRect(outerRRect, innerRRect, paint);

486
    final double currentThumbExtension = CupertinoThumbPainter.extension * currentReactionValue;
487
    final double thumbLeft = lerpDouble(
488 489
      trackRect.left + _kTrackInnerStart - CupertinoThumbPainter.radius,
      trackRect.left + _kTrackInnerEnd - CupertinoThumbPainter.radius - currentThumbExtension,
490
      visualPosition,
491 492
    );
    final double thumbRight = lerpDouble(
493 494
      trackRect.left + _kTrackInnerStart + CupertinoThumbPainter.radius + currentThumbExtension,
      trackRect.left + _kTrackInnerEnd + CupertinoThumbPainter.radius,
495
      visualPosition,
496 497 498
    );
    final double thumbCenterY = offset.dy + size.height / 2.0;

499
    _thumbPainter.paint(canvas, Rect.fromLTRB(
500 501 502 503 504
      thumbLeft,
      thumbCenterY - CupertinoThumbPainter.radius,
      thumbRight,
      thumbCenterY + CupertinoThumbPainter.radius,
    ));
505 506 507
  }

  @override
508
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
509
    super.debugFillProperties(description);
510 511
    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));
512 513
  }
}