slider.dart 18.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 7
// 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;

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

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

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

22 23
/// An iOS-style slider.
///
24 25
/// {@youtube 560 315 https://www.youtube.com/watch?v=ufb4gIPDmEs}
///
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.
///
40 41 42 43 44 45
/// {@tool dartpad}
/// This example shows how to show the current slider value as it changes.
///
/// ** See code in examples/api/lib/cupertino/slider/cupertino_slider.0.dart **
/// {@end-tool}
///
46 47
/// See also:
///
48
///  * <https://developer.apple.com/ios/human-interface-guidelines/controls/sliders/>
49 50 51 52 53 54 55 56 57 58
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.
59 60 61 62
  /// * [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.
63
  const CupertinoSlider({
64
    super.key,
65 66
    required this.value,
    required this.onChanged,
67 68
    this.onChangeStart,
    this.onChangeEnd,
69 70
    this.min = 0.0,
    this.max = 1.0,
71
    this.divisions,
72
    this.activeColor,
73
    this.thumbColor = CupertinoColors.white,
74 75
  }) : assert(value >= min && value <= max),
       assert(divisions == null || divisions > 0);
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

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

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

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

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

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

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

210
  @override
211
  State<CupertinoSlider> createState() => _CupertinoSliderState();
212 213

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

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

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

  void _handleDragEnd(double value) {
    assert(widget.onChangeEnd != null);
238
    widget.onChangeEnd!(lerpDouble(widget.min, widget.max, value)!);
239 240 241 242
  }

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

class _CupertinoSliderRenderObjectWidget extends LeafRenderObjectWidget {
260
  const _CupertinoSliderRenderObjectWidget({
261
    required this.value,
262
    this.divisions,
263 264
    required this.activeColor,
    required this.thumbColor,
265
    this.onChanged,
266 267
    this.onChangeStart,
    this.onChangeEnd,
268
    required this.vsync,
269
  });
270 271

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

  @override
  _RenderCupertinoSlider createRenderObject(BuildContext context) {
282
    assert(debugCheckHasDirectionality(context));
283
    return _RenderCupertinoSlider(
284 285 286
      value: value,
      divisions: divisions,
      activeColor: activeColor,
287 288
      thumbColor: CupertinoDynamicColor.resolve(thumbColor, context),
      trackColor: CupertinoDynamicColor.resolve(CupertinoColors.systemFill, context),
289
      onChanged: onChanged,
290 291
      onChangeStart: onChangeStart,
      onChangeEnd: onChangeEnd,
292
      vsync: vsync,
293
      textDirection: Directionality.of(context),
294
      cursor: kIsWeb ? SystemMouseCursors.click : MouseCursor.defer,
295 296 297 298 299
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderCupertinoSlider renderObject) {
300
    assert(debugCheckHasDirectionality(context));
301 302 303 304
    renderObject
      ..value = value
      ..divisions = divisions
      ..activeColor = activeColor
305 306
      ..thumbColor = CupertinoDynamicColor.resolve(thumbColor, context)
      ..trackColor = CupertinoDynamicColor.resolve(CupertinoColors.systemFill, context)
307
      ..onChanged = onChanged
308 309
      ..onChangeStart = onChangeStart
      ..onChangeEnd = onChangeEnd
310
      ..textDirection = Directionality.of(context);
311 312 313 314 315 316 317 318
    // 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.
319
const Duration _kDiscreteTransitionDuration = Duration(milliseconds: 500);
320 321 322

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

323
class _RenderCupertinoSlider extends RenderConstrainedBox implements MouseTrackerAnnotation {
324
  _RenderCupertinoSlider({
325 326 327 328 329 330
    required double value,
    int? divisions,
    required Color activeColor,
    required Color thumbColor,
    required Color trackColor,
    ValueChanged<double>? onChanged,
331 332
    this.onChangeStart,
    this.onChangeEnd,
333 334
    required TickerProvider vsync,
    required TextDirection textDirection,
335
    MouseCursor cursor = MouseCursor.defer,
336
  }) : assert(value >= 0.0 && value <= 1.0),
337
       _cursor = cursor,
338
       _value = value,
339 340
       _divisions = divisions,
       _activeColor = activeColor,
341
       _thumbColor = thumbColor,
342
       _trackColor = trackColor,
343
       _onChanged = onChanged,
344
       _textDirection = textDirection,
345
       super(additionalConstraints: const BoxConstraints.tightFor(width: _kSliderWidth, height: _kSliderHeight)) {
346
    _drag = HorizontalDragGestureRecognizer()
347 348 349
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
      ..onEnd = _handleDragEnd;
350
    _position = AnimationController(
351 352 353 354 355 356 357 358 359
      value: value,
      duration: _kDiscreteTransitionDuration,
      vsync: vsync,
    )..addListener(markNeedsPaint);
  }

  double get value => _value;
  double _value;
  set value(double newValue) {
360
    assert(newValue >= 0.0 && newValue <= 1.0);
361
    if (newValue == _value) {
362
      return;
363
    }
364
    _value = newValue;
365
    if (divisions != null) {
366
      _position.animateTo(newValue, curve: Curves.fastOutSlowIn);
367
    } else {
368
      _position.value = newValue;
369
    }
370
    markNeedsSemanticsUpdate();
371 372
  }

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

  Color get activeColor => _activeColor;
  Color _activeColor;
  set activeColor(Color value) {
386
    if (value == _activeColor) {
387
      return;
388
    }
389 390 391 392
    _activeColor = value;
    markNeedsPaint();
  }

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

403 404 405
  Color get trackColor => _trackColor;
  Color _trackColor;
  set trackColor(Color value) {
406
    if (value == _trackColor) {
407
      return;
408
    }
409 410 411 412
    _trackColor = value;
    markNeedsPaint();
  }

413 414 415
  ValueChanged<double>? get onChanged => _onChanged;
  ValueChanged<double>? _onChanged;
  set onChanged(ValueChanged<double>? value) {
416
    if (value == _onChanged) {
417
      return;
418
    }
419 420
    final bool wasInteractive = isInteractive;
    _onChanged = value;
421
    if (wasInteractive != isInteractive) {
422
      markNeedsSemanticsUpdate();
423
    }
424
  }
425

426 427
  ValueChanged<double>? onChangeStart;
  ValueChanged<double>? onChangeEnd;
428

429 430 431
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
432
    if (_textDirection == value) {
433
      return;
434
    }
435 436 437 438
    _textDirection = value;
    markNeedsPaint();
  }

439
  late AnimationController _position;
440

441
  late HorizontalDragGestureRecognizer _drag;
442 443 444
  double _currentDragValue = 0.0;

  double get _discretizedCurrentDragValue {
445
    double dragValue = clampDouble(_currentDragValue, 0.0, 1.0);
446
    if (divisions != null) {
447
      dragValue = (dragValue * divisions!).round() / divisions!;
448
    }
449 450 451 452 453
    return dragValue;
  }

  double get _trackLeft => _kPadding;
  double get _trackRight => size.width - _kPadding;
454
  double get _thumbCenter {
455
    final double visualPosition;
456 457 458 459 460 461
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - _value;
      case TextDirection.ltr:
        visualPosition = _value;
    }
462
    return lerpDouble(_trackLeft + CupertinoThumbPainter.radius, _trackRight - CupertinoThumbPainter.radius, visualPosition)!;
463
  }
464 465 466

  bool get isInteractive => onChanged != null;

467
  void _handleDragStart(DragStartDetails details) => _startInteraction(details.globalPosition);
468 469 470 471

  void _handleDragUpdate(DragUpdateDetails details) {
    if (isInteractive) {
      final double extent = math.max(_kPadding, size.width - 2.0 * (_kPadding + CupertinoThumbPainter.radius));
472
      final double valueDelta = details.primaryDelta! / extent;
473 474 475 476 477 478
      switch (textDirection) {
        case TextDirection.rtl:
          _currentDragValue -= valueDelta;
        case TextDirection.ltr:
          _currentDragValue += valueDelta;
      }
479
      onChanged!(_discretizedCurrentDragValue);
480 481 482
    }
  }

483 484 485 486
  void _handleDragEnd(DragEndDetails details) => _endInteraction();

  void _startInteraction(Offset globalPosition) {
    if (isInteractive) {
487
      onChangeStart?.call(_discretizedCurrentDragValue);
488
      _currentDragValue = _value;
489
      onChanged!(_discretizedCurrentDragValue);
490 491 492 493
    }
  }

  void _endInteraction() {
494
    onChangeEnd?.call(_discretizedCurrentDragValue);
495 496 497 498
    _currentDragValue = 0.0;
  }

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

  @override
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
    assert(debugHandleEvent(event, entry));
506
    if (event is PointerDownEvent && isInteractive) {
507
      _drag.addPointer(event);
508
    }
509 510 511 512
  }

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

    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;

534
    final Canvas canvas = context.canvas;
535

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

541
    if (visualPosition < 1.0) {
xster's avatar
xster committed
542
      final Paint paint = Paint()..color = leftColor;
543
      canvas.drawRRect(RRect.fromLTRBXY(trackActive, trackTop, trackRight, trackBottom, 1.0, 1.0), paint);
544 545
    }

546
    final Offset thumbCenter = Offset(trackActive, trackCenter);
547
    CupertinoThumbPainter(color: thumbColor).paint(canvas, Rect.fromCircle(center: thumbCenter, radius: CupertinoThumbPainter.radius));
548 549 550
  }

  @override
551 552
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
553

554
    config.isSemanticBoundary = isInteractive;
555
    config.isSlider = true;
556
    if (isInteractive) {
557
      config.textDirection = textDirection;
558 559
      config.onIncrease = _increaseAction;
      config.onDecrease = _decreaseAction;
560
      config.value = '${(value * 100).round()}%';
561 562
      config.increasedValue = '${(clampDouble(value + _semanticActionUnit, 0.0, 1.0) * 100).round()}%';
      config.decreasedValue = '${(clampDouble(value - _semanticActionUnit, 0.0, 1.0) * 100).round()}%';
563 564 565
    }
  }

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

568
  void _increaseAction() {
569
    if (isInteractive) {
570
      onChanged!(clampDouble(value + _semanticActionUnit, 0.0, 1.0));
571
    }
572 573
  }

574
  void _decreaseAction() {
575
    if (isInteractive) {
576
      onChanged!(clampDouble(value - _semanticActionUnit, 0.0, 1.0));
577
    }
578
  }
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601

  @override
  MouseCursor get cursor => _cursor;
  MouseCursor _cursor;
  set cursor(MouseCursor value) {
    if (_cursor != value) {
      _cursor = value;
      // A repaint is needed in order to trigger a device update of
      // [MouseTracker] so that this new value can be found.
      markNeedsPaint();
    }
  }

  @override
  PointerEnterEventListener? onEnter;

  PointerHoverEventListener? onHover;

  @override
  PointerExitEventListener? onExit;

  @override
  bool get validForMouseTracker => false;
602
}