slider.dart 16.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// 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;

import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';

xster's avatar
xster committed
12
import 'theme.dart';
13 14
import 'thumb_painter.dart';

15 16
// Examples can assume:
// int _cupertinoSliderValue = 1;
17
// void setState(VoidCallback fn) { }
18

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/// An iOS-style slider.
///
/// Used to select from a range of values.
///
/// A slider can be used to select from either a continuous or a discrete set of
/// values. The default is use a continuous range of values from [min] to [max].
/// To use discrete values, use a non-null value for [divisions], which
/// indicates the number of discrete intervals. For example, if [min] is 0.0 and
/// [max] is 50.0 and [divisions] is 5, then the slider can take on the values
/// discrete values 0.0, 10.0, 20.0, 30.0, 40.0, and 50.0.
///
/// The slider itself does not maintain any state. Instead, when the state of
/// the slider changes, the widget calls the [onChanged] callback. Most widgets
/// that use a slider will listen for the [onChanged] callback and rebuild the
/// slider with a new [value] to update the visual appearance of the slider.
///
/// See also:
///
37
///  * <https://developer.apple.com/ios/human-interface-guidelines/controls/sliders/>
38 39 40 41 42 43 44 45 46 47
class CupertinoSlider extends StatefulWidget {
  /// Creates an iOS-style slider.
  ///
  /// The slider itself does not maintain any state. Instead, when the state of
  /// the slider changes, the widget calls the [onChanged] callback. Most widgets
  /// that use a slider will listen for the [onChanged] callback and rebuild the
  /// slider with a new [value] to update the visual appearance of the slider.
  ///
  /// * [value] determines currently selected value for this slider.
  /// * [onChanged] is called when the user selects a new value for the slider.
48 49 50 51
  /// * [onChangeStart] is called when the user starts to select a new value for
  ///   the slider.
  /// * [onChangeEnd] is called when the user is done selecting a new value for
  ///   the slider.
52
  const CupertinoSlider({
53 54 55
    Key key,
    @required this.value,
    @required this.onChanged,
56 57
    this.onChangeStart,
    this.onChangeEnd,
58 59
    this.min = 0.0,
    this.max = 1.0,
60
    this.divisions,
61
    this.activeColor,
62 63 64 65 66 67
  }) : assert(value != null),
       assert(min != null),
       assert(max != null),
       assert(value >= min && value <= max),
       assert(divisions == null || divisions > 0),
       super(key: key);
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

  /// The currently selected value for this slider.
  ///
  /// The slider's thumb is drawn at a position that corresponds to this value.
  final double value;

  /// Called when the user selects a new value for the slider.
  ///
  /// The slider passes the new value to the callback but does not actually
  /// change state until the parent widget rebuilds the slider with the new
  /// value.
  ///
  /// If null, the slider 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
87
  /// CupertinoSlider(
88
  ///   value: _cupertinoSliderValue.toDouble(),
89 90 91 92 93
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   onChanged: (double newValue) {
  ///     setState(() {
94
  ///       _cupertinoSliderValue = newValue.round();
95 96
  ///     });
  ///   },
97
  /// )
98
  /// ```
99
  ///
100 101 102 103 104 105
  /// See also:
  ///
  ///  * [onChangeStart] for a callback that is called when the user starts
  ///    changing the value.
  ///  * [onChangeEnd] for a callback that is called when the user stops
  ///    changing the value.
106 107
  final ValueChanged<double> onChanged;

108 109 110 111 112 113 114 115 116
  /// Called when the user starts selecting a new value for the slider.
  ///
  /// This callback shouldn't be used to update the slider [value] (use
  /// [onChanged] for that), but rather to be notified when the user has started
  /// selecting a new value by starting a drag.
  ///
  /// The value passed will be the last [value] that the slider had before the
  /// change began.
  ///
117
  /// {@tool sample}
118 119
  ///
  /// ```dart
120
  /// CupertinoSlider(
121 122 123 124 125 126 127 128 129 130 131 132 133 134
  ///   value: _cupertinoSliderValue.toDouble(),
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _cupertinoSliderValue = newValue.round();
  ///     });
  ///   },
  ///   onChangeStart: (double startValue) {
  ///     print('Started change at $startValue');
  ///   },
  /// )
  /// ```
135
  /// {@end-tool}
136 137 138 139 140 141 142 143 144 145 146 147 148
  ///
  /// See also:
  ///
  ///  * [onChangeEnd] for a callback that is called when the value change is
  ///    complete.
  final ValueChanged<double> onChangeStart;

  /// Called when the user is done selecting a new value for the slider.
  ///
  /// This callback shouldn't be used to update the slider [value] (use
  /// [onChanged] for that), but rather to know when the user has completed
  /// selecting a new [value] by ending a drag.
  ///
149
  /// {@tool sample}
150 151
  ///
  /// ```dart
152
  /// CupertinoSlider(
153 154 155 156 157 158 159 160 161 162 163 164 165 166
  ///   value: _cupertinoSliderValue.toDouble(),
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _cupertinoSliderValue = newValue.round();
  ///     });
  ///   },
  ///   onChangeEnd: (double newValue) {
  ///     print('Ended change on $newValue');
  ///   },
  /// )
  /// ```
167
  /// {@end-tool}
168 169 170 171 172 173 174
  ///
  /// See also:
  ///
  ///  * [onChangeStart] for a callback that is called when a value change
  ///    begins.
  final ValueChanged<double> onChangeEnd;

175
  /// The minimum value the user can select.
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  ///
  /// Defaults to 0.0.
  final double min;

  /// The maximum value the user can select.
  ///
  /// Defaults to 1.0.
  final double max;

  /// The number of discrete divisions.
  ///
  /// If null, the slider is continuous.
  final int divisions;

  /// The color to use for the portion of the slider that has been selected.
191
  ///
xster's avatar
xster committed
192
  /// Defaults to the [CupertinoTheme]'s primary color if null.
193 194 195
  final Color activeColor;

  @override
196
  _CupertinoSliderState createState() => _CupertinoSliderState();
197 198

  @override
199 200
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
201 202 203
    properties.add(DoubleProperty('value', value));
    properties.add(DoubleProperty('min', min));
    properties.add(DoubleProperty('max', max));
204
  }
205 206 207 208
}

class _CupertinoSliderState extends State<CupertinoSlider> with TickerProviderStateMixin {
  void _handleChanged(double value) {
209
    assert(widget.onChanged != null);
210 211 212 213 214 215 216 217 218 219 220 221 222 223
    final double lerpValue = lerpDouble(widget.min, widget.max, value);
    if (lerpValue != widget.value) {
      widget.onChanged(lerpValue);
    }
  }

  void _handleDragStart(double value) {
    assert(widget.onChangeStart != null);
    widget.onChangeStart(lerpDouble(widget.min, widget.max, value));
  }

  void _handleDragEnd(double value) {
    assert(widget.onChangeEnd != null);
    widget.onChangeEnd(lerpDouble(widget.min, widget.max, value));
224 225 226 227
  }

  @override
  Widget build(BuildContext context) {
228
    return _CupertinoSliderRenderObjectWidget(
229 230
      value: (widget.value - widget.min) / (widget.max - widget.min),
      divisions: widget.divisions,
xster's avatar
xster committed
231
      activeColor: widget.activeColor ?? CupertinoTheme.of(context).primaryColor,
232
      onChanged: widget.onChanged != null ? _handleChanged : null,
233 234
      onChangeStart: widget.onChangeStart != null ? _handleDragStart : null,
      onChangeEnd: widget.onChangeEnd != null ? _handleDragEnd : null,
235 236 237 238 239 240
      vsync: this,
    );
  }
}

class _CupertinoSliderRenderObjectWidget extends LeafRenderObjectWidget {
241
  const _CupertinoSliderRenderObjectWidget({
242 243 244 245 246
    Key key,
    this.value,
    this.divisions,
    this.activeColor,
    this.onChanged,
247 248
    this.onChangeStart,
    this.onChangeEnd,
249 250 251 252 253 254 255
    this.vsync,
  }) : super(key: key);

  final double value;
  final int divisions;
  final Color activeColor;
  final ValueChanged<double> onChanged;
256 257
  final ValueChanged<double> onChangeStart;
  final ValueChanged<double> onChangeEnd;
258 259 260 261
  final TickerProvider vsync;

  @override
  _RenderCupertinoSlider createRenderObject(BuildContext context) {
262
    return _RenderCupertinoSlider(
263 264 265 266
      value: value,
      divisions: divisions,
      activeColor: activeColor,
      onChanged: onChanged,
267 268
      onChangeStart: onChangeStart,
      onChangeEnd: onChangeEnd,
269
      vsync: vsync,
270
      textDirection: Directionality.of(context),
271 272 273 274 275 276 277 278 279
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderCupertinoSlider renderObject) {
    renderObject
      ..value = value
      ..divisions = divisions
      ..activeColor = activeColor
280
      ..onChanged = onChanged
281 282
      ..onChangeStart = onChangeStart
      ..onChangeEnd = onChangeEnd
283
      ..textDirection = Directionality.of(context);
284 285 286 287 288 289
    // Ticker provider cannot change since there's a 1:1 relationship between
    // the _SliderRenderObjectWidget object and the _SliderState object.
  }
}

const double _kPadding = 8.0;
290
const Color _kTrackColor = Color(0xFFB5B5B5);
291 292
const double _kSliderHeight = 2.0 * (CupertinoThumbPainter.radius + _kPadding);
const double _kSliderWidth = 176.0; // Matches Material Design slider.
293
const Duration _kDiscreteTransitionDuration = Duration(milliseconds: 500);
294 295 296

const double _kAdjustmentUnit = 0.1; // Matches iOS implementation of material slider.

297
class _RenderCupertinoSlider extends RenderConstrainedBox {
298
  _RenderCupertinoSlider({
299
    @required double value,
300 301
    int divisions,
    Color activeColor,
302
    ValueChanged<double> onChanged,
303 304
    this.onChangeStart,
    this.onChangeEnd,
305
    TickerProvider vsync,
306
    @required TextDirection textDirection,
307
  }) : assert(value != null && value >= 0.0 && value <= 1.0),
308
       assert(textDirection != null),
309
       _value = value,
310 311
       _divisions = divisions,
       _activeColor = activeColor,
312
       _onChanged = onChanged,
313
       _textDirection = textDirection,
314
       super(additionalConstraints: const BoxConstraints.tightFor(width: _kSliderWidth, height: _kSliderHeight)) {
315
    _drag = HorizontalDragGestureRecognizer()
316 317 318
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
      ..onEnd = _handleDragEnd;
319
    _position = AnimationController(
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
      value: value,
      duration: _kDiscreteTransitionDuration,
      vsync: vsync,
    )..addListener(markNeedsPaint);
  }

  double get value => _value;
  double _value;
  set value(double newValue) {
    assert(newValue != null && newValue >= 0.0 && newValue <= 1.0);
    if (newValue == _value)
      return;
    _value = newValue;
    if (divisions != null)
      _position.animateTo(newValue, curve: Curves.fastOutSlowIn);
    else
      _position.value = newValue;
337
    markNeedsSemanticsUpdate();
338 339 340 341
  }

  int get divisions => _divisions;
  int _divisions;
342 343
  set divisions(int value) {
    if (value == _divisions)
344
      return;
345
    _divisions = value;
346 347 348 349 350 351 352 353 354 355 356 357
    markNeedsPaint();
  }

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

358 359 360 361 362 363 364 365
  ValueChanged<double> get onChanged => _onChanged;
  ValueChanged<double> _onChanged;
  set onChanged(ValueChanged<double> value) {
    if (value == _onChanged)
      return;
    final bool wasInteractive = isInteractive;
    _onChanged = value;
    if (wasInteractive != isInteractive)
366
      markNeedsSemanticsUpdate();
367
  }
368

369 370 371
  ValueChanged<double> onChangeStart;
  ValueChanged<double> onChangeEnd;

372 373 374 375 376 377 378 379 380 381
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    assert(value != null);
    if (_textDirection == value)
      return;
    _textDirection = value;
    markNeedsPaint();
  }

382 383 384 385 386 387 388 389 390 391 392 393 394 395
  AnimationController _position;

  HorizontalDragGestureRecognizer _drag;
  double _currentDragValue = 0.0;

  double get _discretizedCurrentDragValue {
    double dragValue = _currentDragValue.clamp(0.0, 1.0);
    if (divisions != null)
      dragValue = (dragValue * divisions).round() / divisions;
    return dragValue;
  }

  double get _trackLeft => _kPadding;
  double get _trackRight => size.width - _kPadding;
396 397 398 399 400 401 402 403 404 405 406 407
  double get _thumbCenter {
    double visualPosition;
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - _value;
        break;
      case TextDirection.ltr:
        visualPosition = _value;
        break;
    }
    return lerpDouble(_trackLeft + CupertinoThumbPainter.radius, _trackRight - CupertinoThumbPainter.radius, visualPosition);
  }
408 409 410

  bool get isInteractive => onChanged != null;

411
  void _handleDragStart(DragStartDetails details) => _startInteraction(details.globalPosition);
412 413 414 415

  void _handleDragUpdate(DragUpdateDetails details) {
    if (isInteractive) {
      final double extent = math.max(_kPadding, size.width - 2.0 * (_kPadding + CupertinoThumbPainter.radius));
416 417 418 419 420 421 422 423 424
      final double valueDelta = details.primaryDelta / extent;
      switch (textDirection) {
        case TextDirection.rtl:
          _currentDragValue -= valueDelta;
          break;
        case TextDirection.ltr:
          _currentDragValue += valueDelta;
          break;
      }
425 426 427 428
      onChanged(_discretizedCurrentDragValue);
    }
  }

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
  void _handleDragEnd(DragEndDetails details) => _endInteraction();

  void _startInteraction(Offset globalPosition) {
    if (isInteractive) {
      if (onChangeStart != null) {
        onChangeStart(_discretizedCurrentDragValue);
      }
      _currentDragValue = _value;
      onChanged(_discretizedCurrentDragValue);
    }
  }

  void _endInteraction() {
    if (onChangeEnd != null) {
      onChangeEnd(_discretizedCurrentDragValue);
    }
445 446 447 448
    _currentDragValue = 0.0;
  }

  @override
449 450
  bool hitTestSelf(Offset position) {
    return (position.dx - _thumbCenter).abs() < CupertinoThumbPainter.radius + _kPadding;
451 452 453 454 455 456 457 458 459
  }

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

460
  final CupertinoThumbPainter _thumbPainter = CupertinoThumbPainter();
461 462 463

  @override
  void paint(PaintingContext context, Offset offset) {
464 465 466 467 468 469
    double visualPosition;
    Color leftColor;
    Color rightColor;
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - _position.value;
Ian Hickson's avatar
Ian Hickson committed
470 471
        leftColor = _activeColor;
        rightColor = _kTrackColor;
472 473 474
        break;
      case TextDirection.ltr:
        visualPosition = _position.value;
Ian Hickson's avatar
Ian Hickson committed
475 476
        leftColor = _kTrackColor;
        rightColor = _activeColor;
477 478
        break;
    }
479 480 481 482 483 484 485 486

    final double trackCenter = offset.dy + size.height / 2.0;
    final double trackLeft = offset.dx + _trackLeft;
    final double trackTop = trackCenter - 1.0;
    final double trackBottom = trackCenter + 1.0;
    final double trackRight = offset.dx + _trackRight;
    final double trackActive = offset.dx + _thumbCenter;

487
    final Canvas canvas = context.canvas;
488

489
    if (visualPosition > 0.0) {
xster's avatar
xster committed
490
      final Paint paint = Paint()..color = rightColor;
491
      canvas.drawRRect(RRect.fromLTRBXY(trackLeft, trackTop, trackActive, trackBottom, 1.0, 1.0), paint);
492 493
    }

494
    if (visualPosition < 1.0) {
xster's avatar
xster committed
495
      final Paint paint = Paint()..color = leftColor;
496
      canvas.drawRRect(RRect.fromLTRBXY(trackActive, trackTop, trackRight, trackBottom, 1.0, 1.0), paint);
497 498
    }

499 500
    final Offset thumbCenter = Offset(trackActive, trackCenter);
    _thumbPainter.paint(canvas, Rect.fromCircle(center: thumbCenter, radius: CupertinoThumbPainter.radius));
501 502 503
  }

  @override
504 505
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
506

507 508
    config.isSemanticBoundary = isInteractive;
    if (isInteractive) {
509
      config.textDirection = textDirection;
510 511
      config.onIncrease = _increaseAction;
      config.onDecrease = _decreaseAction;
512 513 514
      config.value = '${(value * 100).round()}%';
      config.increasedValue = '${((value + _semanticActionUnit).clamp(0.0, 1.0) * 100).round()}%';
      config.decreasedValue = '${((value - _semanticActionUnit).clamp(0.0, 1.0) * 100).round()}%';
515 516 517 518
    }
  }

  double get _semanticActionUnit => divisions != null ? 1.0 / divisions : _kAdjustmentUnit;
519

520
  void _increaseAction() {
521
    if (isInteractive)
522
      onChanged((value + _semanticActionUnit).clamp(0.0, 1.0));
523 524
  }

525 526 527
  void _decreaseAction() {
    if (isInteractive)
      onChanged((value - _semanticActionUnit).clamp(0.0, 1.0));
528 529
  }
}