slider.dart 56.1 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:async';
6 7
import 'dart:math' as math;

8
import 'package:flutter/cupertino.dart';
9
import 'package:flutter/foundation.dart';
10 11
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
12
import 'package:flutter/scheduler.dart' show timeDilation;
13
import 'package:flutter/services.dart';
14

15
import 'constants.dart';
16
import 'debug.dart';
17
import 'material.dart';
18
import 'material_state.dart';
19
import 'slider_theme.dart';
20 21
import 'theme.dart';

22
// Examples can assume:
23
// int _dollars = 0;
24
// int _duelCommandment = 1;
25
// void setState(VoidCallback fn) { }
26

27 28 29 30 31 32
/// [Slider] uses this callback to paint the value indicator on the overlay.
///
/// Since the value indicator is painted on the Overlay; this method paints the
/// value indicator in a [RenderBox] that appears in the [Overlay].
typedef PaintValueIndicator = void Function(PaintingContext context, Offset offset);

33 34
enum _SliderType { material, adaptive }

35
/// A Material Design slider.
36
///
37 38
/// Used to select from a range of values.
///
39 40
/// {@youtube 560 315 https://www.youtube.com/watch?v=ufb4gIPDmEs}
///
41
/// {@tool dartpad}
42 43 44 45 46 47
/// ![A slider widget, consisting of 5 divisions and showing the default value
/// indicator.](https://flutter.github.io/assets-for-api-docs/assets/material/slider.png)
///
/// The Sliders value is part of the Stateful widget subclass to change the value
/// setState was called.
///
48
/// ** See code in examples/api/lib/material/slider/slider.0.dart **
49 50
/// {@end-tool}
///
51
/// A slider can be used to select from either a continuous or a discrete set of
52 53
/// values. The default is to use a continuous range of values from [min] to
/// [max]. To use discrete values, use a non-null value for [divisions], which
54
/// indicates the number of discrete intervals. For example, if [min] is 0.0 and
55
/// [max] is 50.0 and [divisions] is 5, then the slider can take on the
56
/// discrete values 0.0, 10.0, 20.0, 30.0, 40.0, and 50.0.
57
///
58 59 60 61
/// The terms for the parts of a slider are:
///
///  * The "thumb", which is a shape that slides horizontally when the user
///    drags it.
62
///  * The "track", which is the line that the slider thumb slides along.
63 64 65 66 67 68 69
///  * The "value indicator", which is a shape that pops up when the user
///    is dragging the thumb to indicate the value being selected.
///  * The "active" side of the slider is the side between the thumb and the
///    minimum value.
///  * The "inactive" side of the slider is the side between the thumb and the
///    maximum value.
///
70 71 72
/// The slider will be disabled if [onChanged] is null or if the range given by
/// [min]..[max] is empty (i.e. if [min] is equal to [max]).
///
73 74 75 76
/// The slider widget 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
77 78
/// slider. To know when the value starts to change, or when it is done
/// changing, set the optional callbacks [onChangeStart] and/or [onChangeEnd].
79
///
80
/// By default, a slider will be as wide as possible, centered vertically. When
81
/// given unbounded constraints, it will attempt to make the track 144 pixels
82
/// wide (with margins on each side) and will shrink-wrap vertically.
83
///
84 85
/// Requires one of its ancestors to be a [Material] widget.
///
86 87 88 89
/// Requires one of its ancestors to be a [MediaQuery] widget. Typically, these
/// are introduced by the [MaterialApp] or [WidgetsApp] widget at the top of
/// your application widget tree.
///
90 91 92 93 94 95 96
/// To determine how it should be displayed (e.g. colors, thumb shape, etc.),
/// a slider uses the [SliderThemeData] available from either a [SliderTheme]
/// widget or the [ThemeData.sliderTheme] a [Theme] widget above it in the
/// widget tree. You can also override some of the colors with the [activeColor]
/// and [inactiveColor] properties, although more fine-grained control of the
/// look is achieved using a [SliderThemeData].
///
97
/// See also:
98
///
99 100
///  * [SliderTheme] and [SliderThemeData] for information about controlling
///    the visual appearance of the slider.
101 102
///  * [Radio], for selecting among a set of explicit values.
///  * [Checkbox] and [Switch], for toggling a particular value on or off.
103
///  * <https://material.io/design/components/sliders.html>
104
///  * [MediaQuery], from which the text scale factor is obtained.
105
class Slider extends StatefulWidget {
106
  /// Creates a Material Design slider.
107 108
  ///
  /// The slider itself does not maintain any state. Instead, when the state of
109 110 111 112
  /// 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.
113 114
  ///
  /// * [value] determines currently selected value for this slider.
115 116 117 118 119 120
  /// * [onChanged] is called while the user is selecting a new value for the
  ///   slider.
  /// * [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.
121 122 123 124
  ///
  /// You can override some of the colors with the [activeColor] and
  /// [inactiveColor] properties, although more fine-grained control of the
  /// appearance is achieved using a [SliderThemeData].
125
  const Slider({
126
    super.key,
127 128
    required this.value,
    required this.onChanged,
129 130
    this.onChangeStart,
    this.onChangeEnd,
131 132
    this.min = 0.0,
    this.max = 1.0,
133 134
    this.divisions,
    this.label,
135
    this.activeColor,
136
    this.inactiveColor,
137
    this.thumbColor,
138
    this.mouseCursor,
139
    this.semanticFormatterCallback,
140 141
    this.focusNode,
    this.autofocus = false,
142 143 144 145 146 147
  }) : _sliderType = _SliderType.material,
       assert(value != null),
       assert(min != null),
       assert(max != null),
       assert(min <= max),
       assert(value >= min && value <= max),
148
       assert(divisions == null || divisions > 0);
149

150 151 152 153
  /// Creates an adaptive [Slider] based on the target platform, following
  /// Material design's
  /// [Cross-platform guidelines](https://material.io/design/platform-guidance/cross-platform-adaptation.html).
  ///
154
  /// Creates a [CupertinoSlider] if the target platform is iOS or macOS, creates a
155 156 157 158 159 160 161
  /// Material Design slider otherwise.
  ///
  /// If a [CupertinoSlider] is created, the following parameters are
  /// ignored: [label], [inactiveColor], [semanticFormatterCallback].
  ///
  /// The target platform is based on the current [Theme]: [ThemeData.platform].
  const Slider.adaptive({
162
    super.key,
163 164
    required this.value,
    required this.onChanged,
165 166 167 168 169 170
    this.onChangeStart,
    this.onChangeEnd,
    this.min = 0.0,
    this.max = 1.0,
    this.divisions,
    this.label,
171
    this.mouseCursor,
172 173
    this.activeColor,
    this.inactiveColor,
174
    this.thumbColor,
175
    this.semanticFormatterCallback,
176 177
    this.focusNode,
    this.autofocus = false,
178 179
  }) : _sliderType = _SliderType.adaptive,
       assert(value != null),
180 181
       assert(min != null),
       assert(max != null),
182
       assert(min <= max),
183
       assert(value >= min && value <= max),
184
       assert(divisions == null || divisions > 0);
185

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

191 192
  /// Called during a drag when the user is selecting a new value for the slider
  /// by dragging.
193 194 195 196 197 198
  ///
  /// 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.
199 200 201 202 203
  ///
  /// 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:
  ///
204
  /// {@tool snippet}
205
  ///
206
  /// ```dart
207
  /// Slider(
208 209 210 211 212 213 214 215 216 217
  ///   value: _duelCommandment.toDouble(),
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   label: '$_duelCommandment',
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _duelCommandment = newValue.round();
  ///     });
  ///   },
218
  /// )
219
  /// ```
220
  /// {@end-tool}
221 222 223 224 225 226 227
  ///
  /// 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.
228
  final ValueChanged<double>? onChanged;
229

230 231 232 233 234 235 236 237 238
  /// 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 or with a tap.
  ///
  /// The value passed will be the last [value] that the slider had before the
  /// change began.
  ///
239
  /// {@tool snippet}
240 241
  ///
  /// ```dart
242
  /// Slider(
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
  ///   value: _duelCommandment.toDouble(),
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   label: '$_duelCommandment',
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _duelCommandment = newValue.round();
  ///     });
  ///   },
  ///   onChangeStart: (double startValue) {
  ///     print('Started change at $startValue');
  ///   },
  /// )
  /// ```
258
  /// {@end-tool}
259 260 261 262 263
  ///
  /// See also:
  ///
  ///  * [onChangeEnd] for a callback that is called when the value change is
  ///    complete.
264
  final ValueChanged<double>? onChangeStart;
265 266 267 268 269 270 271

  /// 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 or a click.
  ///
272
  /// {@tool snippet}
273 274
  ///
  /// ```dart
275
  /// Slider(
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  ///   value: _duelCommandment.toDouble(),
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   label: '$_duelCommandment',
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _duelCommandment = newValue.round();
  ///     });
  ///   },
  ///   onChangeEnd: (double newValue) {
  ///     print('Ended change on $newValue');
  ///   },
  /// )
  /// ```
291
  /// {@end-tool}
292 293 294 295 296
  ///
  /// See also:
  ///
  ///  * [onChangeStart] for a callback that is called when a value change
  ///    begins.
297
  final ValueChanged<double>? onChangeEnd;
298

299
  /// The minimum value the user can select.
300
  ///
301 302 303
  /// Defaults to 0.0. Must be less than or equal to [max].
  ///
  /// If the [max] is equal to the [min], then the slider is disabled.
Hixie's avatar
Hixie committed
304
  final double min;
305 306 307

  /// The maximum value the user can select.
  ///
308 309 310
  /// Defaults to 1.0. Must be greater than or equal to [min].
  ///
  /// If the [max] is equal to the [min], then the slider is disabled.
Hixie's avatar
Hixie committed
311
  final double max;
312

313 314 315 316 317
  /// The number of discrete divisions.
  ///
  /// Typically used with [label] to show the current discrete value.
  ///
  /// If null, the slider is continuous.
318
  final int? divisions;
319

320 321
  /// A label to show above the slider when the slider is active and
  /// [SliderThemeData.showValueIndicator] is satisfied.
322
  ///
323 324 325
  /// It is used to display the value of a discrete slider, and it is displayed
  /// as part of the value indicator shape.
  ///
326 327 328 329
  /// The label is rendered using the active [ThemeData]'s [TextTheme.bodyText1]
  /// text style, with the theme data's [ColorScheme.onPrimary] color. The
  /// label's text style can be overridden with
  /// [SliderThemeData.valueIndicatorTextStyle].
330 331 332
  ///
  /// If null, then the value indicator will not be displayed.
  ///
333 334
  /// Ignored if this slider is created with [Slider.adaptive].
  ///
335 336 337 338
  /// See also:
  ///
  ///  * [SliderComponentShape] for how to create a custom value indicator
  ///    shape.
339
  final String? label;
340

341
  /// The color to use for the portion of the slider track that is active.
342
  ///
343 344
  /// The "active" side of the slider is the side between the thumb and the
  /// minimum value.
345
  ///
346 347
  /// Defaults to [SliderThemeData.activeTrackColor] of the current
  /// [SliderTheme].
348 349 350
  ///
  /// Using a [SliderTheme] gives much more fine-grained control over the
  /// appearance of various components of the slider.
351
  final Color? activeColor;
352

353
  /// The color for the inactive portion of the slider track.
354
  ///
355 356
  /// The "inactive" side of the slider is the side between the thumb and the
  /// maximum value.
357
  ///
358
  /// Defaults to the [SliderThemeData.inactiveTrackColor] of the current
359
  /// [SliderTheme].
360
  ///
361 362
  /// Using a [SliderTheme] gives much more fine-grained control over the
  /// appearance of various components of the slider.
363 364
  ///
  /// Ignored if this slider is created with [Slider.adaptive].
365
  final Color? inactiveColor;
366

367 368 369 370 371 372 373 374
  /// The color of the thumb.
  ///
  /// If this color is null:
  /// * [Slider] will use [activeColor].
  /// * [CupertinoSlider] will have a white thumb
  /// (like the native default iOS slider).
  final Color? thumbColor;

375
  /// {@template flutter.material.slider.mouseCursor}
376 377 378 379 380 381
  /// The cursor for a mouse pointer when it enters or is hovering over the
  /// widget.
  ///
  /// If [mouseCursor] is a [MaterialStateProperty<MouseCursor>],
  /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s:
  ///
382
  ///  * [MaterialState.dragged].
383 384 385
  ///  * [MaterialState.hovered].
  ///  * [MaterialState.focused].
  ///  * [MaterialState.disabled].
386
  /// {@endtemplate}
387
  ///
388 389 390 391 392 393 394
  /// If null, then the value of [SliderThemeData.mouseCursor] is used. If that
  /// is also null, then [MaterialStateMouseCursor.clickable] is used.
  ///
  /// See also:
  ///
  ///  * [MaterialStateMouseCursor], which can be used to create a [MouseCursor]
  ///    that is also a [MaterialStateProperty<MouseCursor>].
395
  final MouseCursor? mouseCursor;
396

397 398 399 400 401 402 403
  /// The callback used to create a semantic value from a slider value.
  ///
  /// Defaults to formatting values as a percentage.
  ///
  /// This is used by accessibility frameworks like TalkBack on Android to
  /// inform users what the currently selected value is with more context.
  ///
404
  /// {@tool snippet}
405 406 407 408 409
  ///
  /// In the example below, a slider for currency values is configured to
  /// announce a value with a currency label.
  ///
  /// ```dart
410
  /// Slider(
411 412 413 414 415 416 417 418 419 420 421 422 423 424
  ///   value: _dollars.toDouble(),
  ///   min: 20.0,
  ///   max: 330.0,
  ///   label: '$_dollars dollars',
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _dollars = newValue.round();
  ///     });
  ///   },
  ///   semanticFormatterCallback: (double newValue) {
  ///     return '${newValue.round()} dollars';
  ///   }
  ///  )
  /// ```
425
  /// {@end-tool}
426 427
  ///
  /// Ignored if this slider is created with [Slider.adaptive]
428
  final SemanticFormatterCallback? semanticFormatterCallback;
429

430
  /// {@macro flutter.widgets.Focus.focusNode}
431
  final FocusNode? focusNode;
432 433 434 435

  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

436 437
  final _SliderType _sliderType ;

438
  @override
439
  State<Slider> createState() => _SliderState();
440 441

  @override
442 443
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
444
    properties.add(DoubleProperty('value', value));
445 446 447
    properties.add(ObjectFlagProperty<ValueChanged<double>>('onChanged', onChanged, ifNull: 'disabled'));
    properties.add(ObjectFlagProperty<ValueChanged<double>>.has('onChangeStart', onChangeStart));
    properties.add(ObjectFlagProperty<ValueChanged<double>>.has('onChangeEnd', onChangeEnd));
448 449
    properties.add(DoubleProperty('min', min));
    properties.add(DoubleProperty('max', max));
450 451 452 453 454
    properties.add(IntProperty('divisions', divisions));
    properties.add(StringProperty('label', label));
    properties.add(ColorProperty('activeColor', activeColor));
    properties.add(ColorProperty('inactiveColor', inactiveColor));
    properties.add(ObjectFlagProperty<ValueChanged<double>>.has('semanticFormatterCallback', semanticFormatterCallback));
455 456
    properties.add(ObjectFlagProperty<FocusNode>.has('focusNode', focusNode));
    properties.add(FlagProperty('autofocus', value: autofocus, ifTrue: 'autofocus'));
457
  }
458 459 460
}

class _SliderState extends State<Slider> with TickerProviderStateMixin {
461 462
  static const Duration enableAnimationDuration = Duration(milliseconds: 75);
  static const Duration valueIndicatorAnimationDuration = Duration(milliseconds: 100);
463 464 465

  // Animation controller that is run when the overlay (a.k.a radial reaction)
  // is shown in response to user interaction.
466
  late AnimationController overlayController;
467 468
  // Animation controller that is run when the value indicator is being shown
  // or hidden.
469
  late AnimationController valueIndicatorController;
470
  // Animation controller that is run when enabling/disabling the slider.
471
  late AnimationController enableController;
472 473
  // Animation controller that is run when transitioning between one value
  // and the next on a discrete slider.
474 475
  late AnimationController positionController;
  Timer? interactionTimer;
476 477

  final GlobalKey _renderObjectKey = GlobalKey();
478

479
  // Keyboard mapping for a focused slider.
480
  static const Map<ShortcutActivator, Intent> _traditionalNavShortcutMap = <ShortcutActivator, Intent>{
481 482 483 484 485
      SingleActivator(LogicalKeyboardKey.arrowUp): _AdjustSliderIntent.up(),
      SingleActivator(LogicalKeyboardKey.arrowDown): _AdjustSliderIntent.down(),
      SingleActivator(LogicalKeyboardKey.arrowLeft): _AdjustSliderIntent.left(),
      SingleActivator(LogicalKeyboardKey.arrowRight): _AdjustSliderIntent.right(),
    };
486 487 488 489 490 491 492 493

  // Keyboard mapping for a focused slider when using directional navigation.
  // The vertical inputs are not handled to allow navigating out of the slider.
  static const Map<ShortcutActivator, Intent> _directionalNavShortcutMap = <ShortcutActivator, Intent>{
      SingleActivator(LogicalKeyboardKey.arrowLeft): _AdjustSliderIntent.left(),
      SingleActivator(LogicalKeyboardKey.arrowRight): _AdjustSliderIntent.right(),
    };

494
  // Action mapping for a focused slider.
495
  late Map<Type, Action<Intent>> _actionMap;
496 497

  bool get _enabled => widget.onChanged != null;
498
  // Value Indicator Animation that appears on the Overlay.
499
  PaintValueIndicator? paintValueIndicator;
500

501 502
  bool _dragging = false;

503 504 505
  FocusNode? _focusNode;
  FocusNode get focusNode => widget.focusNode ?? _focusNode!;

506 507 508
  @override
  void initState() {
    super.initState();
509
    overlayController = AnimationController(
510 511 512
      duration: kRadialReactionDuration,
      vsync: this,
    );
513
    valueIndicatorController = AnimationController(
514 515 516
      duration: valueIndicatorAnimationDuration,
      vsync: this,
    );
517
    enableController = AnimationController(
518 519 520
      duration: enableAnimationDuration,
      vsync: this,
    );
521
    positionController = AnimationController(
522
      duration: Duration.zero,
523 524
      vsync: this,
    );
525
    enableController.value = widget.onChanged != null ? 1.0 : 0.0;
526
    positionController.value = _convert(widget.value);
527 528 529 530 531
    _actionMap = <Type, Action<Intent>>{
      _AdjustSliderIntent: CallbackAction<_AdjustSliderIntent>(
        onInvoke: _actionHandler,
      ),
    };
532 533 534 535
    if (widget.focusNode == null) {
      // Only create a new node if the widget doesn't have one.
      _focusNode ??= FocusNode();
    }
536 537 538 539
  }

  @override
  void dispose() {
540
    interactionTimer?.cancel();
541 542
    overlayController.dispose();
    valueIndicatorController.dispose();
543 544
    enableController.dispose();
    positionController.dispose();
545
    if (overlayEntry != null) {
546
      overlayEntry!.remove();
547 548
      overlayEntry = null;
    }
549
    _focusNode?.dispose();
550
    super.dispose();
551 552
  }

Hixie's avatar
Hixie committed
553
  void _handleChanged(double value) {
554
    assert(widget.onChanged != null);
555 556
    final double lerpValue = _lerp(value);
    if (lerpValue != widget.value) {
557
      widget.onChanged!(lerpValue);
558
    }
Hixie's avatar
Hixie committed
559 560
  }

561
  void _handleDragStart(double value) {
562 563
    _dragging = true;
    widget.onChangeStart?.call(_lerp(value));
564 565 566
  }

  void _handleDragEnd(double value) {
567 568
    _dragging = false;
    widget.onChangeEnd?.call(_lerp(value));
569 570
  }

571
  void _actionHandler(_AdjustSliderIntent intent) {
572
    final _RenderSlider renderSlider = _renderObjectKey.currentContext!.findRenderObject()! as _RenderSlider;
573
    final TextDirection textDirection = Directionality.of(_renderObjectKey.currentContext!);
574 575 576 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 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
    switch (intent.type) {
      case _SliderAdjustmentType.right:
        switch (textDirection) {
          case TextDirection.rtl:
            renderSlider.decreaseAction();
            break;
          case TextDirection.ltr:
            renderSlider.increaseAction();
            break;
        }
        break;
      case _SliderAdjustmentType.left:
        switch (textDirection) {
          case TextDirection.rtl:
            renderSlider.increaseAction();
            break;
          case TextDirection.ltr:
            renderSlider.decreaseAction();
            break;
        }
        break;
      case _SliderAdjustmentType.up:
        renderSlider.increaseAction();
        break;
      case _SliderAdjustmentType.down:
        renderSlider.decreaseAction();
        break;
    }
  }

  bool _focused = false;
  void _handleFocusHighlightChanged(bool focused) {
    if (focused != _focused) {
      setState(() { _focused = focused; });
    }
  }

  bool _hovering = false;
  void _handleHoverChanged(bool hovering) {
    if (hovering != _hovering) {
      setState(() { _hovering = hovering; });
    }
  }

618 619 620 621 622 623
  // Returns a number between min and max, proportional to value, which must
  // be between 0.0 and 1.0.
  double _lerp(double value) {
    assert(value >= 0.0);
    assert(value <= 1.0);
    return value * (widget.max - widget.min) + widget.min;
624 625
  }

626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
  double _discretize(double value) {
    assert(widget.divisions != null);
    assert(value >= 0.0 && value <= 1.0);

    final int divisions = widget.divisions!;
    return (value * divisions).round() / divisions;
  }

  double _convert(double value) {
    double ret = _unlerp(value);
    if (widget.divisions != null) {
      ret = _discretize(ret);
    }
    return ret;
  }

642 643 644 645
  // Returns a number between 0.0 and 1.0, given a value between min and max.
  double _unlerp(double value) {
    assert(value <= widget.max);
    assert(value >= widget.min);
646
    return widget.max > widget.min ? (value - widget.min) / (widget.max - widget.min) : 0.0;
647
  }
648

649
  @override
650
  Widget build(BuildContext context) {
651
    assert(debugCheckHasMaterial(context));
652
    assert(debugCheckHasMediaQuery(context));
653

654 655 656 657 658
    switch (widget._sliderType) {
      case _SliderType.material:
        return _buildMaterialSlider(context);

      case _SliderType.adaptive: {
659
        final ThemeData theme = Theme.of(context);
660 661 662 663
        assert(theme.platform != null);
        switch (theme.platform) {
          case TargetPlatform.android:
          case TargetPlatform.fuchsia:
664 665
          case TargetPlatform.linux:
          case TargetPlatform.windows:
666 667
            return _buildMaterialSlider(context);
          case TargetPlatform.iOS:
668
          case TargetPlatform.macOS:
669 670 671 672 673 674 675
            return _buildCupertinoSlider(context);
        }
      }
    }
  }

  Widget _buildMaterialSlider(BuildContext context) {
676
    final ThemeData theme = Theme.of(context);
677 678 679 680
    SliderThemeData sliderTheme = SliderTheme.of(context);

    // If the widget has active or inactive colors specified, then we plug them
    // in to the slider theme as best we can. If the developer wants more
681 682 683 684
    // control than that, then they need to use a SliderTheme. The default
    // colors come from the ThemeData.colorScheme. These colors, along with
    // the default shapes and text styles are aligned to the Material
    // Guidelines.
685

686 687 688 689 690 691 692
    const double defaultTrackHeight = 4;
    const SliderTrackShape defaultTrackShape = RoundedRectSliderTrackShape();
    const SliderTickMarkShape defaultTickMarkShape = RoundSliderTickMarkShape();
    const SliderComponentShape defaultOverlayShape = RoundSliderOverlayShape();
    const SliderComponentShape defaultThumbShape = RoundSliderThumbShape();
    const SliderComponentShape defaultValueIndicatorShape = RectangularSliderValueIndicatorShape();
    const ShowValueIndicator defaultShowValueIndicator = ShowValueIndicator.onlyForDiscrete;
693 694 695 696 697

    // The value indicator's color is not the same as the thumb and active track
    // (which can be defined by activeColor) if the
    // RectangularSliderValueIndicatorShape is used. In all other cases, the
    // value indicator is assumed to be the same as the active color.
698
    final SliderComponentShape valueIndicatorShape = sliderTheme.valueIndicatorShape ?? defaultValueIndicatorShape;
699
    final Color valueIndicatorColor;
700 701 702 703 704 705
    if (valueIndicatorShape is RectangularSliderValueIndicatorShape) {
      valueIndicatorColor = sliderTheme.valueIndicatorColor ?? Color.alphaBlend(theme.colorScheme.onSurface.withOpacity(0.60), theme.colorScheme.surface.withOpacity(0.90));
    } else {
      valueIndicatorColor = widget.activeColor ?? sliderTheme.valueIndicatorColor ?? theme.colorScheme.primary;
    }

706
    sliderTheme = sliderTheme.copyWith(
707
      trackHeight: sliderTheme.trackHeight ?? defaultTrackHeight,
708 709 710 711 712 713 714 715
      activeTrackColor: widget.activeColor ?? sliderTheme.activeTrackColor ?? theme.colorScheme.primary,
      inactiveTrackColor: widget.inactiveColor ?? sliderTheme.inactiveTrackColor ?? theme.colorScheme.primary.withOpacity(0.24),
      disabledActiveTrackColor: sliderTheme.disabledActiveTrackColor ?? theme.colorScheme.onSurface.withOpacity(0.32),
      disabledInactiveTrackColor: sliderTheme.disabledInactiveTrackColor ?? theme.colorScheme.onSurface.withOpacity(0.12),
      activeTickMarkColor: widget.inactiveColor ?? sliderTheme.activeTickMarkColor ?? theme.colorScheme.onPrimary.withOpacity(0.54),
      inactiveTickMarkColor: widget.activeColor ?? sliderTheme.inactiveTickMarkColor ?? theme.colorScheme.primary.withOpacity(0.54),
      disabledActiveTickMarkColor: sliderTheme.disabledActiveTickMarkColor ?? theme.colorScheme.onPrimary.withOpacity(0.12),
      disabledInactiveTickMarkColor: sliderTheme.disabledInactiveTickMarkColor ?? theme.colorScheme.onSurface.withOpacity(0.12),
716
      thumbColor: widget.thumbColor ?? widget.activeColor ?? sliderTheme.thumbColor ?? theme.colorScheme.primary,
717
      disabledThumbColor: sliderTheme.disabledThumbColor ?? Color.alphaBlend(theme.colorScheme.onSurface.withOpacity(.38), theme.colorScheme.surface),
718
      overlayColor: widget.activeColor?.withOpacity(0.12) ?? sliderTheme.overlayColor ?? theme.colorScheme.primary.withOpacity(0.12),
719
      valueIndicatorColor: valueIndicatorColor,
720 721 722 723
      trackShape: sliderTheme.trackShape ?? defaultTrackShape,
      tickMarkShape: sliderTheme.tickMarkShape ?? defaultTickMarkShape,
      thumbShape: sliderTheme.thumbShape ?? defaultThumbShape,
      overlayShape: sliderTheme.overlayShape ?? defaultOverlayShape,
724
      valueIndicatorShape: valueIndicatorShape,
725
      showValueIndicator: sliderTheme.showValueIndicator ?? defaultShowValueIndicator,
726
      valueIndicatorTextStyle: sliderTheme.valueIndicatorTextStyle ?? theme.textTheme.bodyText1!.copyWith(
727 728 729
        color: theme.colorScheme.onPrimary,
      ),
    );
730 731 732 733 734 735 736 737 738
    final Set<MaterialState> states = <MaterialState>{
      if (!_enabled) MaterialState.disabled,
      if (_hovering) MaterialState.hovered,
      if (_focused) MaterialState.focused,
      if (_dragging) MaterialState.dragged,
    };
    final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs<MouseCursor?>(widget.mouseCursor, states)
      ?? sliderTheme.mouseCursor?.resolve(states)
      ?? MaterialStateMouseCursor.clickable.resolve(states);
739

740 741 742
    // This size is used as the max bounds for the painting of the value
    // indicators It must be kept in sync with the function with the same name
    // in range_slider.dart.
743
    Size screenSize() => MediaQuery.of(context).size;
744

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    VoidCallback? handleDidGainAccessibilityFocus;
    switch (theme.platform) {
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.iOS:
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
        break;
      case TargetPlatform.windows:
        handleDidGainAccessibilityFocus = () {
          // Automatically activate the slider when it receives a11y focus.
          if (!focusNode.hasFocus && focusNode.canRequestFocus) {
            focusNode.requestFocus();
          }
        };
        break;
    }

763 764 765 766 767 768 769 770 771 772
    final Map<ShortcutActivator, Intent> shortcutMap;
    switch (MediaQuery.of(context).navigationMode) {
      case NavigationMode.directional:
        shortcutMap = _directionalNavShortcutMap;
        break;
      case NavigationMode.traditional:
        shortcutMap = _traditionalNavShortcutMap;
        break;
    }

773 774
    return Semantics(
      container: true,
775
      slider: true,
776
      onDidGainAccessibilityFocus: handleDidGainAccessibilityFocus,
777 778
      child: FocusableActionDetector(
        actions: _actionMap,
779
        shortcuts: shortcutMap,
780
        focusNode: focusNode,
781 782 783 784 785 786 787 788 789
        autofocus: widget.autofocus,
        enabled: _enabled,
        onShowFocusHighlight: _handleFocusHighlightChanged,
        onShowHoverHighlight: _handleHoverChanged,
        mouseCursor: effectiveMouseCursor,
        child: CompositedTransformTarget(
          link: _layerLink,
          child: _SliderRenderObjectWidget(
            key: _renderObjectKey,
790
            value: _convert(widget.value),
791 792 793
            divisions: widget.divisions,
            label: widget.label,
            sliderTheme: sliderTheme,
794
            textScaleFactor: MediaQuery.of(context).textScaleFactor,
795
            screenSize: screenSize(),
796
            onChanged: (widget.onChanged != null) && (widget.max > widget.min) ? _handleChanged : null,
797 798
            onChangeStart: _handleDragStart,
            onChangeEnd: _handleDragEnd,
799 800 801 802 803
            state: this,
            semanticFormatterCallback: widget.semanticFormatterCallback,
            hasFocus: _focused,
            hovering: _hovering,
          ),
804
        ),
805
      ),
806 807
    );
  }
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823

  Widget _buildCupertinoSlider(BuildContext context) {
    // The render box of a slider has a fixed height but takes up the available
    // width. Wrapping the [CupertinoSlider] in this manner will help maintain
    // the same size.
    return SizedBox(
      width: double.infinity,
      child: CupertinoSlider(
        value: widget.value,
        onChanged: widget.onChanged,
        onChangeStart: widget.onChangeStart,
        onChangeEnd: widget.onChangeEnd,
        min: widget.min,
        max: widget.max,
        divisions: widget.divisions,
        activeColor: widget.activeColor,
824
        thumbColor: widget.thumbColor ?? CupertinoColors.white,
825 826 827
      ),
    );
  }
828 829
  final LayerLink _layerLink = LayerLink();

830
  OverlayEntry? overlayEntry;
831 832 833 834 835 836 837 838 839 840 841 842 843

  void showValueIndicator() {
    if (overlayEntry == null) {
      overlayEntry = OverlayEntry(
        builder: (BuildContext context) {
          return CompositedTransformFollower(
            link: _layerLink,
            child: _ValueIndicatorRenderObjectWidget(
              state: this,
            ),
          );
        },
      );
844
      Overlay.of(context)!.insert(overlayEntry!);
845 846
    }
  }
847 848
}

849

850
class _SliderRenderObjectWidget extends LeafRenderObjectWidget {
851
  const _SliderRenderObjectWidget({
852
    super.key,
853 854 855 856 857 858 859 860 861 862 863 864 865
    required this.value,
    required this.divisions,
    required this.label,
    required this.sliderTheme,
    required this.textScaleFactor,
    required this.screenSize,
    required this.onChanged,
    required this.onChangeStart,
    required this.onChangeEnd,
    required this.state,
    required this.semanticFormatterCallback,
    required this.hasFocus,
    required this.hovering,
866
  });
867 868

  final double value;
869 870
  final int? divisions;
  final String? label;
871
  final SliderThemeData sliderTheme;
872 873
  final double textScaleFactor;
  final Size screenSize;
874 875 876 877
  final ValueChanged<double>? onChanged;
  final ValueChanged<double>? onChangeStart;
  final ValueChanged<double>? onChangeEnd;
  final SemanticFormatterCallback? semanticFormatterCallback;
878
  final _SliderState state;
879 880
  final bool hasFocus;
  final bool hovering;
881

882
  @override
883
  _RenderSlider createRenderObject(BuildContext context) {
884
    return _RenderSlider(
885 886 887
      value: value,
      divisions: divisions,
      label: label,
888
      sliderTheme: sliderTheme,
889 890
      textScaleFactor: textScaleFactor,
      screenSize: screenSize,
891
      onChanged: onChanged,
892 893
      onChangeStart: onChangeStart,
      onChangeEnd: onChangeEnd,
894
      state: state,
895
      textDirection: Directionality.of(context),
896
      semanticFormatterCallback: semanticFormatterCallback,
897
      platform: Theme.of(context).platform,
898 899
      hasFocus: hasFocus,
      hovering: hovering,
900
      gestureSettings: MediaQuery.of(context).gestureSettings,
901 902
    );
  }
903

904
  @override
905
  void updateRenderObject(BuildContext context, _RenderSlider renderObject) {
906
    renderObject
907 908
      // We should update the `divisions` ahead of `value`, because the `value`
      // setter dependent on the `divisions`.
909
      ..divisions = divisions
910
      ..value = value
911
      ..label = label
912
      ..sliderTheme = sliderTheme
913 914
      ..textScaleFactor = textScaleFactor
      ..screenSize = screenSize
915
      ..onChanged = onChanged
916 917
      ..onChangeStart = onChangeStart
      ..onChangeEnd = onChangeEnd
918
      ..textDirection = Directionality.of(context)
919
      ..semanticFormatterCallback = semanticFormatterCallback
920
      ..platform = Theme.of(context).platform
921
      ..hasFocus = hasFocus
922 923
      ..hovering = hovering
      ..gestureSettings = MediaQuery.of(context).gestureSettings;
924 925
    // Ticker provider cannot change since there's a 1:1 relationship between
    // the _SliderRenderObjectWidget object and the _SliderState object.
926 927 928
  }
}

929
class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
930
  _RenderSlider({
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
    required double value,
    required int? divisions,
    required String? label,
    required SliderThemeData sliderTheme,
    required double textScaleFactor,
    required Size screenSize,
    required TargetPlatform platform,
    required ValueChanged<double>? onChanged,
    required SemanticFormatterCallback? semanticFormatterCallback,
    required this.onChangeStart,
    required this.onChangeEnd,
    required _SliderState state,
    required TextDirection textDirection,
    required bool hasFocus,
    required bool hovering,
946
    required DeviceGestureSettings gestureSettings,
947
  }) : assert(value != null && value >= 0.0 && value <= 1.0),
948 949 950 951 952 953 954 955 956 957 958 959 960
        assert(state != null),
        assert(textDirection != null),
        _platform = platform,
        _semanticFormatterCallback = semanticFormatterCallback,
        _label = label,
        _value = value,
        _divisions = divisions,
        _sliderTheme = sliderTheme,
        _textScaleFactor = textScaleFactor,
        _screenSize = screenSize,
        _onChanged = onChanged,
        _state = state,
        _textDirection = textDirection,
961
        _hasFocus = hasFocus,
962
        _hovering = hovering {
Ian Hickson's avatar
Ian Hickson committed
963
    _updateLabelPainter();
964 965
    final GestureArenaTeam team = GestureArenaTeam();
    _drag = HorizontalDragGestureRecognizer()
966
      ..team = team
967 968
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
969
      ..onEnd = _handleDragEnd
970 971
      ..onCancel = _endInteraction
      ..gestureSettings = gestureSettings;
972
    _tap = TapGestureRecognizer()
973
      ..team = team
974
      ..onTapDown = _handleTapDown
975 976
      ..onTapUp = _handleTapUp
      ..gestureSettings = gestureSettings;
977
    _overlayAnimation = CurvedAnimation(
978 979 980
      parent: _state.overlayController,
      curve: Curves.fastOutSlowIn,
    );
981
    _valueIndicatorAnimation = CurvedAnimation(
982
      parent: _state.valueIndicatorController,
983
      curve: Curves.fastOutSlowIn,
984 985
    )..addStatusListener((AnimationStatus status) {
      if (status == AnimationStatus.dismissed && _state.overlayEntry != null) {
986
        _state.overlayEntry!.remove();
987 988 989
        _state.overlayEntry = null;
      }
    });
990
    _enableAnimation = CurvedAnimation(
991 992 993
      parent: _state.enableController,
      curve: Curves.easeInOut,
    );
994
  }
995 996
  static const Duration _positionAnimationDuration = Duration(milliseconds: 75);
  static const Duration _minimumInteractionTime = Duration(milliseconds: 500);
997 998 999 1000 1001 1002 1003 1004

  // This value is the touch target, 48, multiplied by 3.
  static const double _minPreferredTrackWidth = 144.0;

  // Compute the largest width and height needed to paint the slider shapes,
  // other than the track shape. It is assumed that these shapes are vertically
  // centered on the track.
  double get _maxSliderPartWidth => _sliderPartSizes.map((Size size) => size.width).reduce(math.max);
1005
  double get _maxSliderPartHeight => _sliderPartSizes.map((Size size) => size.height).reduce(math.max);
1006
  List<Size> get _sliderPartSizes => <Size>[
1007 1008 1009
    _sliderTheme.overlayShape!.getPreferredSize(isInteractive, isDiscrete),
    _sliderTheme.thumbShape!.getPreferredSize(isInteractive, isDiscrete),
    _sliderTheme.tickMarkShape!.getPreferredSize(isEnabled: isInteractive, sliderTheme: sliderTheme),
1010
  ];
1011
  double get _minPreferredTrackHeight => _sliderTheme.trackHeight!;
1012

1013
  final _SliderState _state;
1014 1015 1016
  late Animation<double> _overlayAnimation;
  late Animation<double> _valueIndicatorAnimation;
  late Animation<double> _enableAnimation;
1017
  final TextPainter _labelPainter = TextPainter();
1018 1019
  late HorizontalDragGestureRecognizer _drag;
  late TapGestureRecognizer _tap;
1020 1021 1022
  bool _active = false;
  double _currentDragValue = 0.0;

1023 1024 1025
  // This rect is used in gesture calculations, where the gesture coordinates
  // are relative to the sliders origin. Therefore, the offset is passed as
  // (0,0).
1026
  Rect get _trackRect => _sliderTheme.trackShape!.getPreferredRect(
1027 1028 1029 1030
    parentBox: this,
    sliderTheme: _sliderTheme,
    isDiscrete: false,
  );
1031 1032 1033

  bool get isInteractive => onChanged != null;

1034
  bool get isDiscrete => divisions != null && divisions! > 0;
1035

1036 1037
  double get value => _value;
  double _value;
1038
  set value(double newValue) {
1039
    assert(newValue != null && newValue >= 0.0 && newValue <= 1.0);
1040 1041
    final double convertedValue = isDiscrete ? _discretize(newValue) : newValue;
    if (convertedValue == _value) {
1042
      return;
1043 1044 1045
    }
    _value = convertedValue;
    if (isDiscrete) {
1046 1047 1048 1049 1050 1051 1052
      // Reset the duration to match the distance that we're traveling, so that
      // whatever the distance, we still do it in _positionAnimationDuration,
      // and if we get re-targeted in the middle, it still takes that long to
      // get to the new location.
      final double distance = (_value - _state.positionController.value).abs();
      _state.positionController.duration = distance != 0.0
        ? _positionAnimationDuration * (1.0 / distance)
1053
        : Duration.zero;
1054 1055 1056 1057
      _state.positionController.animateTo(convertedValue, curve: Curves.easeInOut);
    } else {
      _state.positionController.value = convertedValue;
    }
1058 1059 1060
    markNeedsSemanticsUpdate();
  }

1061 1062 1063 1064 1065 1066
  DeviceGestureSettings? get gestureSettings => _drag.gestureSettings;
  set gestureSettings(DeviceGestureSettings? gestureSettings) {
    _drag.gestureSettings = gestureSettings;
    _tap.gestureSettings = gestureSettings;
  }

1067 1068 1069
  TargetPlatform _platform;
  TargetPlatform get platform => _platform;
  set platform(TargetPlatform value) {
1070
    if (_platform == value) {
1071
      return;
1072
    }
1073 1074 1075 1076
    _platform = value;
    markNeedsSemanticsUpdate();
  }

1077 1078 1079
  SemanticFormatterCallback? _semanticFormatterCallback;
  SemanticFormatterCallback? get semanticFormatterCallback => _semanticFormatterCallback;
  set semanticFormatterCallback(SemanticFormatterCallback? value) {
1080
    if (_semanticFormatterCallback == value) {
1081
      return;
1082
    }
1083 1084
    _semanticFormatterCallback = value;
    markNeedsSemanticsUpdate();
1085 1086
  }

1087 1088 1089
  int? get divisions => _divisions;
  int? _divisions;
  set divisions(int? value) {
1090
    if (value == _divisions) {
1091
      return;
1092
    }
1093
    _divisions = value;
1094 1095 1096
    markNeedsPaint();
  }

1097 1098 1099
  String? get label => _label;
  String? _label;
  set label(String? value) {
1100
    if (value == _label) {
1101
      return;
1102
    }
1103
    _label = value;
Ian Hickson's avatar
Ian Hickson committed
1104
    _updateLabelPainter();
1105 1106
  }

1107 1108 1109 1110
  SliderThemeData get sliderTheme => _sliderTheme;
  SliderThemeData _sliderTheme;
  set sliderTheme(SliderThemeData value) {
    if (value == _sliderTheme) {
1111
      return;
1112 1113
    }
    _sliderTheme = value;
1114 1115 1116
    markNeedsPaint();
  }

1117 1118 1119 1120
  double get textScaleFactor => _textScaleFactor;
  double _textScaleFactor;
  set textScaleFactor(double value) {
    if (value == _textScaleFactor) {
1121
      return;
1122
    }
1123
    _textScaleFactor = value;
1124 1125 1126
    _updateLabelPainter();
  }

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
  Size get screenSize => _screenSize;
  Size _screenSize;
  set screenSize(Size value) {
    if (value == _screenSize) {
      return;
    }
    _screenSize = value;
    markNeedsPaint();
  }

1137 1138 1139
  ValueChanged<double>? get onChanged => _onChanged;
  ValueChanged<double>? _onChanged;
  set onChanged(ValueChanged<double>? value) {
1140
    if (value == _onChanged) {
1141
      return;
1142
    }
1143 1144 1145
    final bool wasInteractive = isInteractive;
    _onChanged = value;
    if (wasInteractive != isInteractive) {
1146 1147 1148 1149 1150
      if (isInteractive) {
        _state.enableController.forward();
      } else {
        _state.enableController.reverse();
      }
1151
      markNeedsPaint();
1152
      markNeedsSemanticsUpdate();
1153 1154
    }
  }
1155

1156 1157
  ValueChanged<double>? onChangeStart;
  ValueChanged<double>? onChangeEnd;
1158

1159 1160 1161 1162
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    assert(value != null);
1163
    if (value == _textDirection) {
1164
      return;
1165
    }
1166
    _textDirection = value;
Ian Hickson's avatar
Ian Hickson committed
1167 1168 1169
    _updateLabelPainter();
  }

1170 1171 1172 1173 1174
  /// True if this slider has the input focus.
  bool get hasFocus => _hasFocus;
  bool _hasFocus;
  set hasFocus(bool value) {
    assert(value != null);
1175
    if (value == _hasFocus) {
1176
      return;
1177
    }
1178 1179
    _hasFocus = value;
    _updateForFocusOrHover(_hasFocus);
1180
    markNeedsSemanticsUpdate();
1181 1182 1183 1184 1185 1186 1187
  }

  /// True if this slider is being hovered over by a pointer.
  bool get hovering => _hovering;
  bool _hovering;
  set hovering(bool value) {
    assert(value != null);
1188
    if (value == _hovering) {
1189
      return;
1190
    }
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    _hovering = value;
    _updateForFocusOrHover(_hovering);
  }

  void _updateForFocusOrHover(bool hasFocusOrIsHovering) {
    if (hasFocusOrIsHovering) {
      _state.overlayController.forward();
      if (showValueIndicator) {
        _state.valueIndicatorController.forward();
      }
    } else {
      _state.overlayController.reverse();
      if (showValueIndicator) {
        _state.valueIndicatorController.reverse();
      }
    }
  }
1208

1209
  bool get showValueIndicator {
1210
    switch (_sliderTheme.showValueIndicator!) {
1211
      case ShowValueIndicator.onlyForDiscrete:
1212
        return isDiscrete;
1213
      case ShowValueIndicator.onlyForContinuous:
1214
        return !isDiscrete;
1215
      case ShowValueIndicator.always:
1216
        return true;
1217
      case ShowValueIndicator.never:
1218
        return false;
1219 1220 1221
    }
  }

1222 1223 1224
  double get _adjustmentUnit {
    switch (_platform) {
      case TargetPlatform.iOS:
1225
      case TargetPlatform.macOS:
1226
        // Matches iOS implementation of material slider.
1227 1228 1229
        return 0.1;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
1230 1231 1232
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        // Matches Android implementation of material slider.
1233 1234 1235 1236
        return 0.05;
    }
  }

Ian Hickson's avatar
Ian Hickson committed
1237 1238 1239
  void _updateLabelPainter() {
    if (label != null) {
      _labelPainter
1240
        ..text = TextSpan(
1241 1242 1243
          style: _sliderTheme.valueIndicatorTextStyle,
          text: label,
        )
Ian Hickson's avatar
Ian Hickson committed
1244
        ..textDirection = textDirection
1245
        ..textScaleFactor = textScaleFactor
Ian Hickson's avatar
Ian Hickson committed
1246 1247 1248 1249 1250 1251 1252 1253
        ..layout();
    } else {
      _labelPainter.text = null;
    }
    // Changing the textDirection can result in the layout changing, because the
    // bidi algorithm might line up the glyphs differently which can result in
    // different ligatures, different shapes, etc. So we always markNeedsLayout.
    markNeedsLayout();
1254 1255
  }

1256 1257 1258 1259 1260 1261 1262
  @override
  void systemFontsDidChange() {
    super.systemFontsDidChange();
    _labelPainter.markNeedsLayout();
    _updateLabelPainter();
  }

1263 1264 1265
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
1266 1267
    _overlayAnimation.addListener(markNeedsPaint);
    _valueIndicatorAnimation.addListener(markNeedsPaint);
1268 1269 1270 1271 1272 1273
    _enableAnimation.addListener(markNeedsPaint);
    _state.positionController.addListener(markNeedsPaint);
  }

  @override
  void detach() {
1274 1275
    _overlayAnimation.removeListener(markNeedsPaint);
    _valueIndicatorAnimation.removeListener(markNeedsPaint);
1276 1277 1278 1279 1280
    _enableAnimation.removeListener(markNeedsPaint);
    _state.positionController.removeListener(markNeedsPaint);
    super.detach();
  }

1281 1282 1283 1284 1285 1286 1287 1288 1289
  double _getValueFromVisualPosition(double visualPosition) {
    switch (textDirection) {
      case TextDirection.rtl:
        return 1.0 - visualPosition;
      case TextDirection.ltr:
        return visualPosition;
    }
  }

1290
  double _getValueFromGlobalPosition(Offset globalPosition) {
1291
    final double visualPosition = (globalToLocal(globalPosition).dx - _trackRect.left) / _trackRect.width;
1292
    return _getValueFromVisualPosition(visualPosition);
1293 1294
  }

1295
  double _discretize(double value) {
1296
    double result = clampDouble(value, 0.0, 1.0);
1297
    if (isDiscrete) {
1298
      result = (result * divisions!).round() / divisions!;
1299
    }
1300 1301
    return result;
  }
1302

1303
  void _startInteraction(Offset globalPosition) {
1304
    _state.showValueIndicator();
1305
    if (!_active && isInteractive) {
1306
      _active = true;
1307 1308 1309
      // We supply the *current* value as the start location, so that if we have
      // a tap, it consists of a call to onChangeStart with the previous value and
      // a call to onChangeEnd with the new value.
1310
      onChangeStart?.call(_discretize(value));
1311
      _currentDragValue = _getValueFromGlobalPosition(globalPosition);
1312
      onChanged!(_discretize(_currentDragValue));
1313 1314 1315
      _state.overlayController.forward();
      if (showValueIndicator) {
        _state.valueIndicatorController.forward();
1316
        _state.interactionTimer?.cancel();
1317
        _state.interactionTimer = Timer(_minimumInteractionTime * timeDilation, () {
1318 1319 1320
          _state.interactionTimer = null;
          if (!_active &&
              _state.valueIndicatorController.status == AnimationStatus.completed) {
1321 1322 1323 1324
            _state.valueIndicatorController.reverse();
          }
        });
      }
1325 1326 1327 1328
    }
  }

  void _endInteraction() {
1329 1330 1331 1332
    if (!_state.mounted) {
      return;
    }

1333
    if (_active && _state.mounted) {
1334
      onChangeEnd?.call(_discretize(_currentDragValue));
1335 1336
      _active = false;
      _currentDragValue = 0.0;
1337
      _state.overlayController.reverse();
1338

1339
      if (showValueIndicator && _state.interactionTimer == null) {
1340 1341
        _state.valueIndicatorController.reverse();
      }
1342 1343 1344
    }
  }

1345 1346 1347
  void _handleDragStart(DragStartDetails details) {
    _startInteraction(details.globalPosition);
  }
1348

1349
  void _handleDragUpdate(DragUpdateDetails details) {
1350 1351 1352 1353
    if (!_state.mounted) {
      return;
    }

1354
    if (isInteractive) {
1355
      final double valueDelta = details.primaryDelta! / _trackRect.width;
1356 1357 1358 1359 1360 1361 1362 1363
      switch (textDirection) {
        case TextDirection.rtl:
          _currentDragValue -= valueDelta;
          break;
        case TextDirection.ltr:
          _currentDragValue += valueDelta;
          break;
      }
1364
      onChanged!(_discretize(_currentDragValue));
1365 1366 1367
    }
  }

1368 1369 1370
  void _handleDragEnd(DragEndDetails details) {
    _endInteraction();
  }
1371

1372 1373 1374
  void _handleTapDown(TapDownDetails details) {
    _startInteraction(details.globalPosition);
  }
1375

1376 1377 1378
  void _handleTapUp(TapUpDetails details) {
    _endInteraction();
  }
1379

1380
  @override
1381
  bool hitTestSelf(Offset position) => true;
1382

1383
  @override
Ian Hickson's avatar
Ian Hickson committed
1384
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
1385
    assert(debugHandleEvent(event, entry));
1386 1387
    if (event is PointerDownEvent && isInteractive) {
      // We need to add the drag first so that it has priority.
1388
      _drag.addPointer(event);
1389 1390
      _tap.addPointer(event);
    }
1391 1392
  }

1393
  @override
1394
  double computeMinIntrinsicWidth(double height) => _minPreferredTrackWidth + _maxSliderPartWidth;
1395 1396

  @override
1397
  double computeMaxIntrinsicWidth(double height) => _minPreferredTrackWidth + _maxSliderPartWidth;
1398 1399

  @override
1400
  double computeMinIntrinsicHeight(double width) => math.max(_minPreferredTrackHeight, _maxSliderPartHeight);
1401 1402

  @override
1403
  double computeMaxIntrinsicHeight(double width) => math.max(_minPreferredTrackHeight, _maxSliderPartHeight);
1404 1405 1406 1407 1408

  @override
  bool get sizedByParent => true;

  @override
1409 1410
  Size computeDryLayout(BoxConstraints constraints) {
    return Size(
1411
      constraints.hasBoundedWidth ? constraints.maxWidth : _minPreferredTrackWidth + _maxSliderPartWidth,
1412
      constraints.hasBoundedHeight ? constraints.maxHeight : math.max(_minPreferredTrackHeight, _maxSliderPartHeight),
1413 1414 1415
    );
  }

1416
  @override
1417
  void paint(PaintingContext context, Offset offset) {
1418
    final double value = _state.positionController.value;
1419

1420 1421 1422
    // The visual position is the position of the thumb from 0 to 1 from left
    // to right. In left to right, this is the same as the value, but it is
    // reversed for right to left text.
1423
    final double visualPosition;
1424 1425 1426 1427 1428 1429 1430 1431
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - value;
        break;
      case TextDirection.ltr:
        visualPosition = value;
        break;
    }
1432

1433
    final Rect trackRect = _sliderTheme.trackShape!.getPreferredRect(
1434 1435 1436
      parentBox: this,
      offset: offset,
      sliderTheme: _sliderTheme,
1437
      isDiscrete: isDiscrete,
1438
    );
1439
    final Offset thumbCenter = Offset(trackRect.left + visualPosition * trackRect.width, trackRect.center.dy);
1440

1441
    _sliderTheme.trackShape!.paint(
1442 1443 1444 1445 1446 1447 1448 1449
      context,
      offset,
      parentBox: this,
      sliderTheme: _sliderTheme,
      enableAnimation: _enableAnimation,
      textDirection: _textDirection,
      thumbCenter: thumbCenter,
      isDiscrete: isDiscrete,
1450
      isEnabled: isInteractive,
1451 1452
    );

1453
    if (!_overlayAnimation.isDismissed) {
1454
      _sliderTheme.overlayShape!.paint(
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
        context,
        thumbCenter,
        activationAnimation: _overlayAnimation,
        enableAnimation: _enableAnimation,
        isDiscrete: isDiscrete,
        labelPainter: _labelPainter,
        parentBox: this,
        sliderTheme: _sliderTheme,
        textDirection: _textDirection,
        value: _value,
1465 1466
        textScaleFactor: _textScaleFactor,
        sizeWithOverflow: screenSize.isEmpty ? size : screenSize,
1467 1468 1469 1470
      );
    }

    if (isDiscrete) {
1471
      final double tickMarkWidth = _sliderTheme.tickMarkShape!.getPreferredSize(
1472 1473 1474
        isEnabled: isInteractive,
        sliderTheme: _sliderTheme,
      ).width;
1475
      final double padding = trackRect.height;
1476
      final double adjustedTrackWidth = trackRect.width - padding;
1477
      // If the tick marks would be too dense, don't bother painting them.
1478
      if (adjustedTrackWidth / divisions! >= 3.0 * tickMarkWidth) {
1479
        final double dy = trackRect.center.dy;
1480 1481
        for (int i = 0; i <= divisions!; i++) {
          final double value = i / divisions!;
1482 1483
          // The ticks are mapped to be within the track, so the tick mark width
          // must be subtracted from the track width.
1484
          final double dx = trackRect.left + value * adjustedTrackWidth + padding / 2;
1485
          final Offset tickMarkOffset = Offset(dx, dy);
1486
          _sliderTheme.tickMarkShape!.paint(
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
            context,
            tickMarkOffset,
            parentBox: this,
            sliderTheme: _sliderTheme,
            enableAnimation: _enableAnimation,
            textDirection: _textDirection,
            thumbCenter: thumbCenter,
            isEnabled: isInteractive,
          );
        }
1497 1498 1499 1500
      }
    }

    if (isInteractive && label != null && !_valueIndicatorAnimation.isDismissed) {
1501
      if (showValueIndicator) {
1502
        _state.paintValueIndicator = (PaintingContext context, Offset offset) {
1503
          if (attached) {
1504
            _sliderTheme.valueIndicatorShape!.paint(
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
              context,
              offset + thumbCenter,
              activationAnimation: _valueIndicatorAnimation,
              enableAnimation: _enableAnimation,
              isDiscrete: isDiscrete,
              labelPainter: _labelPainter,
              parentBox: this,
              sliderTheme: _sliderTheme,
              textDirection: _textDirection,
              value: _value,
              textScaleFactor: textScaleFactor,
              sizeWithOverflow: screenSize.isEmpty ? size : screenSize,
            );
          }
1519
        };
1520
      }
1521
    }
Adam Barth's avatar
Adam Barth committed
1522

1523
    _sliderTheme.thumbShape!.paint(
1524 1525
      context,
      thumbCenter,
1526
      activationAnimation: _overlayAnimation,
1527 1528 1529 1530 1531 1532 1533
      enableAnimation: _enableAnimation,
      isDiscrete: isDiscrete,
      labelPainter: _labelPainter,
      parentBox: this,
      sliderTheme: _sliderTheme,
      textDirection: _textDirection,
      value: _value,
1534 1535
      textScaleFactor: textScaleFactor,
      sizeWithOverflow: screenSize.isEmpty ? size : screenSize,
1536
    );
1537
  }
1538 1539

  @override
1540 1541
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
1542

1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
    // The Slider widget has its own Focus widget with semantics information,
    // and we want that semantics node to collect the semantics information here
    // so that it's all in the same node: otherwise Talkback sees that the node
    // has focusable children, and it won't focus the Slider's Focus widget
    // because it thinks the Focus widget's node doesn't have anything to say
    // (which it doesn't, but this child does). Aggregating the semantic
    // information into one node means that Talkback will recognize that it has
    // something to say and focus it when it receives keyboard focus.
    // (See https://github.com/flutter/flutter/issues/57038 for context).
    config.isSemanticBoundary = false;

    config.isEnabled = isInteractive;
    config.textDirection = textDirection;
1556
    if (isInteractive) {
1557 1558
      config.onIncrease = increaseAction;
      config.onDecrease = decreaseAction;
1559
    }
1560

1561
    if (semanticFormatterCallback != null) {
1562
      config.value = semanticFormatterCallback!(_state._lerp(value));
1563 1564
      config.increasedValue = semanticFormatterCallback!(_state._lerp(clampDouble(value + _semanticActionUnit, 0.0, 1.0)));
      config.decreasedValue = semanticFormatterCallback!(_state._lerp(clampDouble(value - _semanticActionUnit, 0.0, 1.0)));
1565 1566
    } else {
      config.value = '${(value * 100).round()}%';
1567 1568
      config.increasedValue = '${(clampDouble(value + _semanticActionUnit, 0.0, 1.0) * 100).round()}%';
      config.decreasedValue = '${(clampDouble(value - _semanticActionUnit, 0.0, 1.0) * 100).round()}%';
1569 1570 1571
    }
  }

1572
  double get _semanticActionUnit => divisions != null ? 1.0 / divisions! : _adjustmentUnit;
1573

1574
  void increaseAction() {
1575
    if (isInteractive) {
1576
      onChanged!(clampDouble(value + _semanticActionUnit, 0.0, 1.0));
1577
    }
1578 1579
  }

1580
  void decreaseAction() {
1581
    if (isInteractive) {
1582
      onChanged!(clampDouble(value - _semanticActionUnit, 0.0, 1.0));
1583
    }
1584
  }
1585
}
1586

1587 1588
class _AdjustSliderIntent extends Intent {
  const _AdjustSliderIntent({
1589
    required this.type,
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
  });

  const _AdjustSliderIntent.right() : type = _SliderAdjustmentType.right;

  const _AdjustSliderIntent.left() : type = _SliderAdjustmentType.left;

  const _AdjustSliderIntent.up() : type = _SliderAdjustmentType.up;

  const _AdjustSliderIntent.down() : type = _SliderAdjustmentType.down;

  final _SliderAdjustmentType type;
}

enum _SliderAdjustmentType {
  right,
  left,
  up,
  down,
}

1610 1611
class _ValueIndicatorRenderObjectWidget extends LeafRenderObjectWidget {
  const _ValueIndicatorRenderObjectWidget({
1612
    required this.state,
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
  });

  final _SliderState state;

  @override
  _RenderValueIndicator createRenderObject(BuildContext context) {
    return _RenderValueIndicator(
      state: state,
    );
  }
  @override
  void updateRenderObject(BuildContext context, _RenderValueIndicator renderObject) {
    renderObject._state = state;
  }
}

class _RenderValueIndicator extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
  _RenderValueIndicator({
1631
    required _SliderState state,
1632 1633 1634 1635 1636 1637
  }) : _state = state {
    _valueIndicatorAnimation = CurvedAnimation(
      parent: _state.valueIndicatorController,
      curve: Curves.fastOutSlowIn,
    );
  }
1638
  late Animation<double> _valueIndicatorAnimation;
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
  _SliderState _state;

  @override
  bool get sizedByParent => true;

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    _valueIndicatorAnimation.addListener(markNeedsPaint);
    _state.positionController.addListener(markNeedsPaint);
  }

  @override
  void detach() {
    _valueIndicatorAnimation.removeListener(markNeedsPaint);
    _state.positionController.removeListener(markNeedsPaint);
    super.detach();
  }

  @override
  void paint(PaintingContext context, Offset offset) {
1660
    _state.paintValueIndicator?.call(context, offset);
1661
  }
1662 1663 1664 1665 1666

  @override
  Size computeDryLayout(BoxConstraints constraints) {
    return constraints.smallest;
  }
1667
}