slider.dart 17.8 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11
// 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';

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

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

20 21
/// An iOS-style slider.
///
22 23
/// {@youtube 560 315 https://www.youtube.com/watch?v=ufb4gIPDmEs}
///
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
/// 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:
///
40
///  * <https://developer.apple.com/ios/human-interface-guidelines/controls/sliders/>
41 42 43 44 45 46 47 48 49 50
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.
51 52 53 54
  /// * [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.
55
  const CupertinoSlider({
56 57 58
    Key? key,
    required this.value,
    required this.onChanged,
59 60
    this.onChangeStart,
    this.onChangeEnd,
61 62
    this.min = 0.0,
    this.max = 1.0,
63
    this.divisions,
64
    this.activeColor,
65
    this.thumbColor = CupertinoColors.white,
66 67 68 69 70
  }) : assert(value != null),
       assert(min != null),
       assert(max != null),
       assert(value >= min && value <= max),
       assert(divisions == null || divisions > 0),
71
       assert(thumbColor != null),
72
       super(key: key);
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

  /// 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
92
  /// CupertinoSlider(
93
  ///   value: _cupertinoSliderValue.toDouble(),
94 95 96 97 98
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   onChanged: (double newValue) {
  ///     setState(() {
99
  ///       _cupertinoSliderValue = newValue.round();
100 101
  ///     });
  ///   },
102
  /// )
103
  /// ```
104
  ///
105 106 107 108 109 110
  /// 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.
111
  final ValueChanged<double>? onChanged;
112

113 114 115 116 117 118 119 120 121
  /// 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.
  ///
122
  /// {@tool snippet}
123 124
  ///
  /// ```dart
125
  /// CupertinoSlider(
126 127 128 129 130 131 132 133 134 135 136 137 138 139
  ///   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');
  ///   },
  /// )
  /// ```
140
  /// {@end-tool}
141 142 143 144 145
  ///
  /// See also:
  ///
  ///  * [onChangeEnd] for a callback that is called when the value change is
  ///    complete.
146
  final ValueChanged<double>? onChangeStart;
147 148 149 150 151 152 153

  /// 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.
  ///
154
  /// {@tool snippet}
155 156
  ///
  /// ```dart
157
  /// CupertinoSlider(
158 159 160 161 162 163 164 165 166 167 168 169 170 171
  ///   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');
  ///   },
  /// )
  /// ```
172
  /// {@end-tool}
173 174 175 176 177
  ///
  /// See also:
  ///
  ///  * [onChangeStart] for a callback that is called when a value change
  ///    begins.
178
  final ValueChanged<double>? onChangeEnd;
179

180
  /// The minimum value the user can select.
181 182 183 184 185 186 187 188 189 190 191 192
  ///
  /// 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.
193
  final int? divisions;
194 195

  /// The color to use for the portion of the slider that has been selected.
196
  ///
xster's avatar
xster committed
197
  /// Defaults to the [CupertinoTheme]'s primary color if null.
198
  final Color? activeColor;
199

200 201 202 203 204 205 206
  /// The color to use for the thumb of the slider.
  ///
  /// Thumb color must not be null.
  ///
  /// Defaults to [CupertinoColors.white].
  final Color thumbColor;

207
  @override
208
  _CupertinoSliderState createState() => _CupertinoSliderState();
209 210

  @override
211 212
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
213 214 215
    properties.add(DoubleProperty('value', value));
    properties.add(DoubleProperty('min', min));
    properties.add(DoubleProperty('max', max));
216
  }
217 218 219 220
}

class _CupertinoSliderState extends State<CupertinoSlider> with TickerProviderStateMixin {
  void _handleChanged(double value) {
221
    assert(widget.onChanged != null);
222
    final double lerpValue = lerpDouble(widget.min, widget.max, value)!;
223
    if (lerpValue != widget.value) {
224
      widget.onChanged!(lerpValue);
225 226 227 228 229
    }
  }

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

  void _handleDragEnd(double value) {
    assert(widget.onChangeEnd != null);
235
    widget.onChangeEnd!(lerpDouble(widget.min, widget.max, value)!);
236 237 238 239
  }

  @override
  Widget build(BuildContext context) {
240
    return _CupertinoSliderRenderObjectWidget(
241 242
      value: (widget.value - widget.min) / (widget.max - widget.min),
      divisions: widget.divisions,
243 244
      activeColor: CupertinoDynamicColor.resolve(
        widget.activeColor ?? CupertinoTheme.of(context).primaryColor,
245
        context,
246
      )!,
247
      thumbColor: widget.thumbColor,
248
      onChanged: widget.onChanged != null ? _handleChanged : null,
249 250
      onChangeStart: widget.onChangeStart != null ? _handleDragStart : null,
      onChangeEnd: widget.onChangeEnd != null ? _handleDragEnd : null,
251 252 253 254 255 256
      vsync: this,
    );
  }
}

class _CupertinoSliderRenderObjectWidget extends LeafRenderObjectWidget {
257
  const _CupertinoSliderRenderObjectWidget({
258 259
    Key? key,
    required this.value,
260
    this.divisions,
261 262
    required this.activeColor,
    required this.thumbColor,
263
    this.onChanged,
264 265
    this.onChangeStart,
    this.onChangeEnd,
266
    required this.vsync,
267 268 269
  }) : super(key: key);

  final double value;
270
  final int? divisions;
271
  final Color activeColor;
272
  final Color thumbColor;
273 274 275
  final ValueChanged<double>? onChanged;
  final ValueChanged<double>? onChangeStart;
  final ValueChanged<double>? onChangeEnd;
276 277 278 279
  final TickerProvider vsync;

  @override
  _RenderCupertinoSlider createRenderObject(BuildContext context) {
280
    assert(debugCheckHasDirectionality(context));
281
    return _RenderCupertinoSlider(
282 283 284
      value: value,
      divisions: divisions,
      activeColor: activeColor,
285 286
      thumbColor: CupertinoDynamicColor.resolve(thumbColor, context)!,
      trackColor: CupertinoDynamicColor.resolve(CupertinoColors.systemFill, context)!,
287
      onChanged: onChanged,
288 289
      onChangeStart: onChangeStart,
      onChangeEnd: onChangeEnd,
290
      vsync: vsync,
291
      textDirection: Directionality.of(context)!,
292 293 294 295 296
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderCupertinoSlider renderObject) {
297
    assert(debugCheckHasDirectionality(context));
298 299 300 301
    renderObject
      ..value = value
      ..divisions = divisions
      ..activeColor = activeColor
302 303
      ..thumbColor = CupertinoDynamicColor.resolve(thumbColor, context)!
      ..trackColor = CupertinoDynamicColor.resolve(CupertinoColors.systemFill, context)!
304
      ..onChanged = onChanged
305 306
      ..onChangeStart = onChangeStart
      ..onChangeEnd = onChangeEnd
307
      ..textDirection = Directionality.of(context)!;
308 309 310 311 312 313 314 315
    // Ticker provider cannot change since there's a 1:1 relationship between
    // the _SliderRenderObjectWidget object and the _SliderState object.
  }
}

const double _kPadding = 8.0;
const double _kSliderHeight = 2.0 * (CupertinoThumbPainter.radius + _kPadding);
const double _kSliderWidth = 176.0; // Matches Material Design slider.
316
const Duration _kDiscreteTransitionDuration = Duration(milliseconds: 500);
317 318 319

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

320
class _RenderCupertinoSlider extends RenderConstrainedBox {
321
  _RenderCupertinoSlider({
322 323 324 325 326 327
    required double value,
    int? divisions,
    required Color activeColor,
    required Color thumbColor,
    required Color trackColor,
    ValueChanged<double>? onChanged,
328 329
    this.onChangeStart,
    this.onChangeEnd,
330 331
    required TickerProvider vsync,
    required TextDirection textDirection,
332
  }) : assert(value != null && value >= 0.0 && value <= 1.0),
333
       assert(textDirection != null),
334
       _value = value,
335 336
       _divisions = divisions,
       _activeColor = activeColor,
337
       _thumbColor = thumbColor,
338
       _trackColor = trackColor,
339
       _onChanged = onChanged,
340
       _textDirection = textDirection,
341
       super(additionalConstraints: const BoxConstraints.tightFor(width: _kSliderWidth, height: _kSliderHeight)) {
342
    _drag = HorizontalDragGestureRecognizer()
343 344 345
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
      ..onEnd = _handleDragEnd;
346
    _position = AnimationController(
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
      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;
364
    markNeedsSemanticsUpdate();
365 366
  }

367 368 369
  int? get divisions => _divisions;
  int? _divisions;
  set divisions(int? value) {
370
    if (value == _divisions)
371
      return;
372
    _divisions = value;
373 374 375 376 377 378 379 380 381 382 383 384
    markNeedsPaint();
  }

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

385 386 387 388 389 390 391 392 393
  Color get thumbColor => _thumbColor;
  Color _thumbColor;
  set thumbColor(Color value) {
    if (value == _thumbColor)
      return;
    _thumbColor = value;
    markNeedsPaint();
  }

394 395 396 397 398 399 400 401 402
  Color get trackColor => _trackColor;
  Color _trackColor;
  set trackColor(Color value) {
    if (value == _trackColor)
      return;
    _trackColor = value;
    markNeedsPaint();
  }

403 404 405
  ValueChanged<double>? get onChanged => _onChanged;
  ValueChanged<double>? _onChanged;
  set onChanged(ValueChanged<double>? value) {
406 407 408 409 410
    if (value == _onChanged)
      return;
    final bool wasInteractive = isInteractive;
    _onChanged = value;
    if (wasInteractive != isInteractive)
411
      markNeedsSemanticsUpdate();
412
  }
413

414 415
  ValueChanged<double>? onChangeStart;
  ValueChanged<double>? onChangeEnd;
416

417 418 419 420 421 422 423 424 425 426
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    assert(value != null);
    if (_textDirection == value)
      return;
    _textDirection = value;
    markNeedsPaint();
  }

427
  late AnimationController _position;
428

429
  late HorizontalDragGestureRecognizer _drag;
430 431 432
  double _currentDragValue = 0.0;

  double get _discretizedCurrentDragValue {
433
    double dragValue = _currentDragValue.clamp(0.0, 1.0);
434
    if (divisions != null)
435
      dragValue = (dragValue * divisions!).round() / divisions!;
436 437 438 439 440
    return dragValue;
  }

  double get _trackLeft => _kPadding;
  double get _trackRight => size.width - _kPadding;
441
  double get _thumbCenter {
442
    final double visualPosition;
443 444 445 446 447 448 449 450
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - _value;
        break;
      case TextDirection.ltr:
        visualPosition = _value;
        break;
    }
451
    return lerpDouble(_trackLeft + CupertinoThumbPainter.radius, _trackRight - CupertinoThumbPainter.radius, visualPosition)!;
452
  }
453 454 455

  bool get isInteractive => onChanged != null;

456
  void _handleDragStart(DragStartDetails details) => _startInteraction(details.globalPosition);
457 458 459 460

  void _handleDragUpdate(DragUpdateDetails details) {
    if (isInteractive) {
      final double extent = math.max(_kPadding, size.width - 2.0 * (_kPadding + CupertinoThumbPainter.radius));
461
      final double valueDelta = details.primaryDelta! / extent;
462 463 464 465 466 467 468 469
      switch (textDirection) {
        case TextDirection.rtl:
          _currentDragValue -= valueDelta;
          break;
        case TextDirection.ltr:
          _currentDragValue += valueDelta;
          break;
      }
470
      onChanged!(_discretizedCurrentDragValue);
471 472 473
    }
  }

474 475 476 477 478
  void _handleDragEnd(DragEndDetails details) => _endInteraction();

  void _startInteraction(Offset globalPosition) {
    if (isInteractive) {
      if (onChangeStart != null) {
479
        onChangeStart!(_discretizedCurrentDragValue);
480 481
      }
      _currentDragValue = _value;
482
      onChanged!(_discretizedCurrentDragValue);
483 484 485 486 487
    }
  }

  void _endInteraction() {
    if (onChangeEnd != null) {
488
      onChangeEnd!(_discretizedCurrentDragValue);
489
    }
490 491 492 493
    _currentDragValue = 0.0;
  }

  @override
494 495
  bool hitTestSelf(Offset position) {
    return (position.dx - _thumbCenter).abs() < CupertinoThumbPainter.radius + _kPadding;
496 497 498 499 500 501 502 503 504 505 506
  }

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

  @override
  void paint(PaintingContext context, Offset offset) {
507 508 509
    final double visualPosition;
    final Color leftColor;
    final Color rightColor;
510 511 512
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - _position.value;
Ian Hickson's avatar
Ian Hickson committed
513
        leftColor = _activeColor;
514
        rightColor = trackColor;
515 516 517
        break;
      case TextDirection.ltr:
        visualPosition = _position.value;
518
        leftColor = trackColor;
Ian Hickson's avatar
Ian Hickson committed
519
        rightColor = _activeColor;
520 521
        break;
    }
522 523 524 525 526 527 528 529

    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;

530
    final Canvas canvas = context.canvas;
531

532
    if (visualPosition > 0.0) {
xster's avatar
xster committed
533
      final Paint paint = Paint()..color = rightColor;
534
      canvas.drawRRect(RRect.fromLTRBXY(trackLeft, trackTop, trackActive, trackBottom, 1.0, 1.0), paint);
535 536
    }

537
    if (visualPosition < 1.0) {
xster's avatar
xster committed
538
      final Paint paint = Paint()..color = leftColor;
539
      canvas.drawRRect(RRect.fromLTRBXY(trackActive, trackTop, trackRight, trackBottom, 1.0, 1.0), paint);
540 541
    }

542
    final Offset thumbCenter = Offset(trackActive, trackCenter);
543
    CupertinoThumbPainter(color: thumbColor).paint(canvas, Rect.fromCircle(center: thumbCenter, radius: CupertinoThumbPainter.radius));
544 545 546
  }

  @override
547 548
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
549

550 551
    config.isSemanticBoundary = isInteractive;
    if (isInteractive) {
552
      config.textDirection = textDirection;
553 554
      config.onIncrease = _increaseAction;
      config.onDecrease = _decreaseAction;
555 556 557
      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()}%';
558 559 560
    }
  }

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

563
  void _increaseAction() {
564
    if (isInteractive)
565
      onChanged!((value + _semanticActionUnit).clamp(0.0, 1.0));
566 567
  }

568 569
  void _decreaseAction() {
    if (isInteractive)
570
      onChanged!((value - _semanticActionUnit).clamp(0.0, 1.0));
571 572
  }
}