range_slider.dart 65.1 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 12 13 14 15 16
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:math' as math;
import 'dart:ui' as ui;

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart' show timeDilation;
import 'package:flutter/widgets.dart';

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

// Examples can assume:
22 23
// RangeValues _rangeValues = const RangeValues(0.3, 0.7);
// RangeValues _dollarsRange = const RangeValues(50, 100);
24 25
// void setState(VoidCallback fn) { }

26 27 28 29 30
/// [RangeSlider] 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 PaintRangeValueIndicator = void Function(PaintingContext context, Offset offset);

31 32 33 34
/// A Material Design range slider.
///
/// Used to select a range from a range of values.
///
35 36
/// {@youtube 560 315 https://www.youtube.com/watch?v=ufb4gIPDmEs}
///
37
/// {@tool dartpad}
38 39 40 41 42 43 44
/// ![A range slider widget, consisting of 5 divisions and showing the default
/// value indicator.](https://flutter.github.io/assets-for-api-docs/assets/material/range_slider.png)
///
/// This range values are in intervals of 20 because the Range Slider has 5
/// divisions, from 0 to 100. This means are values are split between 0, 20, 40,
/// 60, 80, and 100. The range values are initialized with 40 and 80 in this demo.
///
45
/// ** See code in examples/api/lib/material/range_slider/range_slider.0.dart **
46 47
/// {@end-tool}
///
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
/// A range slider can be used to select from either a continuous or a discrete
/// set of 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
/// 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
/// discrete values 0.0, 10.0, 20.0, 30.0, 40.0, and 50.0.
///
/// The terms for the parts of a slider are:
///
///  * The "thumbs", which are the shapes that slide horizontally when the user
///    drags them to change the selected range.
///  * The "track", which is the horizontal line that the thumbs can be dragged
///    along.
///  * The "tick marks", which mark the discrete values of a discrete slider.
///  * The "overlay", which is a highlight that's drawn over a thumb in response
///    to a user tap-down gesture.
///  * The "value indicators", which are the shapes that pop up when the user
///    is dragging a thumb to show the value being selected.
///  * The "active" segment of the slider is the segment between the two thumbs.
///  * The "inactive" slider segments are the two track intervals outside of the
///    slider's thumbs.
///
/// The range 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]).
///
/// The range 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 range slider will listen for the [onChanged] callback
76
/// and rebuild the slider with new [values] to update the visual appearance of
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
/// the slider. To know when the value starts to change, or when it is done
/// changing, set the optional callbacks [onChangeStart] and/or [onChangeEnd].
///
/// By default, a slider will be as wide as possible, centered vertically. When
/// given unbounded constraints, it will attempt to make the track 144 pixels
/// wide (including margins on each side) and will shrink-wrap vertically.
///
/// Requires one of its ancestors to be a [Material] widget. This is typically
/// provided by a [Scaffold] widget.
///
/// Requires one of its ancestors to be a [MediaQuery] widget. Typically, a
/// [MediaQuery] widget is introduced by the [MaterialApp] or [WidgetsApp]
/// widget at the top of your application widget tree.
///
/// 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] inside 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 colors, and other visual properties is achieved using a
/// [SliderThemeData].
///
/// See also:
///
///  * [SliderTheme] and [SliderThemeData] for information about controlling
///    the visual appearance of the slider.
///  * [Slider], for a single-valued slider.
///  * [Radio], for selecting among a set of explicit values.
///  * [Checkbox] and [Switch], for toggling a particular value on or off.
///  * <https://material.io/design/components/sliders.html>
///  * [MediaQuery], from which the text scale factor is obtained.
class RangeSlider extends StatefulWidget {
  /// Creates a Material Design range slider.
  ///
  /// The range 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 range slider will listen for the [onChanged] callback
114
  /// and rebuild the slider with new [values] to update the visual appearance of
115 116 117
  /// the slider. To know when the value starts to change, or when it is done
  /// changing, set the optional callbacks [onChangeStart] and/or [onChangeEnd].
  ///
118
  /// * [values], which determines currently selected values for this range
119 120 121 122 123 124 125 126 127 128 129 130 131
  ///   slider.
  /// * [onChanged], which is called while the user is selecting a new value for
  ///   the range slider.
  /// * [onChangeStart], which is called when the user starts to select a new
  ///   value for the range slider.
  /// * [onChangeEnd], which is called when the user is done selecting a new
  ///   value for the range slider.
  ///
  /// 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].
  ///
  /// The [values], [min], [max] must not be null. The [min] must be less than
132 133
  /// or equal to the [max]. [values].start must be less than or equal to
  /// [values].end. [values].start and [values].end must be greater than or
134 135 136
  /// equal to the [min] and less than or equal to the [max]. The [divisions]
  /// must be null or greater than 0.
  RangeSlider({
137
    super.key,
138 139
    required this.values,
    required this.onChanged,
140 141 142 143 144 145 146 147
    this.onChangeStart,
    this.onChangeEnd,
    this.min = 0.0,
    this.max = 1.0,
    this.divisions,
    this.labels,
    this.activeColor,
    this.inactiveColor,
148 149
    this.overlayColor,
    this.mouseCursor,
150
    this.semanticFormatterCallback,
151
  }) : assert(min <= max),
152 153 154
       assert(values.start <= values.end),
       assert(values.start >= min && values.start <= max),
       assert(values.end >= min && values.end <= max),
155
       assert(divisions == null || divisions > 0);
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

  /// The currently selected values for this range slider.
  ///
  /// The slider's thumbs are drawn at horizontal positions that corresponds to
  /// these values.
  final RangeValues values;

  /// Called when the user is selecting a new value for the slider by dragging.
  ///
  /// The slider passes the new values to the callback but does not actually
  /// change state until the parent widget rebuilds the slider with the new
  /// values.
  ///
  /// 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:
  ///
175
  /// {@tool snippet}
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  ///
  /// ```dart
  /// RangeSlider(
  ///   values: _rangeValues,
  ///   min: 1.0,
  ///   max: 10.0,
  ///   onChanged: (RangeValues newValues) {
  ///     setState(() {
  ///       _rangeValues = newValues;
  ///     });
  ///   },
  /// )
  /// ```
  /// {@end-tool}
  ///
  /// See also:
  ///
193
  ///  * [onChangeStart], which is called when the user starts changing the
194 195
  ///    values.
  ///  * [onChangeEnd], which is called when the user stops changing the values.
196
  final ValueChanged<RangeValues>? onChanged;
197 198 199 200 201 202 203 204 205 206

  /// Called when the user starts selecting new values for the slider.
  ///
  /// This callback shouldn't be used to update the slider [values] (use
  /// [onChanged] for that). Rather, it should be used to be notified when the
  /// user has started selecting a new value by starting a drag or with a tap.
  ///
  /// The values passed will be the last [values] that the slider had before the
  /// change began.
  ///
207
  /// {@tool snippet}
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
  ///
  /// ```dart
  /// RangeSlider(
  ///   values: _rangeValues,
  ///   min: 1.0,
  ///   max: 10.0,
  ///   onChanged: (RangeValues newValues) {
  ///     setState(() {
  ///       _rangeValues = newValues;
  ///     });
  ///   },
  ///   onChangeStart: (RangeValues startValues) {
  ///     print('Started change at $startValues');
  ///   },
  /// )
  /// ```
  /// {@end-tool}
  ///
  /// See also:
  ///
  ///  * [onChangeEnd] for a callback that is called when the value change is
  ///    complete.
230
  final ValueChanged<RangeValues>? onChangeStart;
231 232 233 234 235 236 237 238 239 240 241

  /// Called when the user is done selecting new values for the slider.
  ///
  /// This differs from [onChanged] because it is only called once at the end
  /// of the interaction, while [onChanged] is called as the value is getting
  /// updated within the interaction.
  ///
  /// This callback shouldn't be used to update the slider [values] (use
  /// [onChanged] for that). Rather, it should be used to know when the user has
  /// completed selecting a new [values] by ending a drag or a click.
  ///
242
  /// {@tool snippet}
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
  ///
  /// ```dart
  /// RangeSlider(
  ///   values: _rangeValues,
  ///   min: 1.0,
  ///   max: 10.0,
  ///   onChanged: (RangeValues newValues) {
  ///     setState(() {
  ///       _rangeValues = newValues;
  ///     });
  ///   },
  ///   onChangeEnd: (RangeValues endValues) {
  ///     print('Ended change at $endValues');
  ///   },
  /// )
  /// ```
  /// {@end-tool}
  ///
  /// See also:
  ///
  ///  * [onChangeStart] for a callback that is called when a value change
  ///    begins.
265
  final ValueChanged<RangeValues>? onChangeEnd;
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285

  /// The minimum value the user can select.
  ///
  /// 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.
  final double min;

  /// The maximum value the user can select.
  ///
  /// 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.
  final double max;

  /// The number of discrete divisions.
  ///
  /// Typically used with [labels] to show the current discrete values.
  ///
  /// If null, the slider is continuous.
286
  final int? divisions;
287

288 289 290
  /// Labels to show as text in the [SliderThemeData.rangeValueIndicatorShape]
  /// when the slider is active and [SliderThemeData.showValueIndicator]
  /// is satisfied.
291 292 293 294
  ///
  /// There are two labels: one for the start thumb and one for the end thumb.
  ///
  /// Each label is rendered using the active [ThemeData]'s
295
  /// [TextTheme.bodyLarge] text style, with the theme data's
296
  /// [ColorScheme.onPrimary] color. The label's text style can be overridden
297
  /// with [SliderThemeData.valueIndicatorTextStyle].
298 299 300 301 302 303 304
  ///
  /// If null, then the value indicator will not be displayed.
  ///
  /// See also:
  ///
  ///  * [RangeSliderValueIndicatorShape] for how to create a custom value
  ///    indicator shape.
305
  final RangeLabels? labels;
306 307 308 309 310 311 312 313

  /// The color of the track's active segment, i.e. the span of track between
  /// the thumbs.
  ///
  /// Defaults to [ColorScheme.primary].
  ///
  /// Using a [SliderTheme] gives more fine-grained control over the
  /// appearance of various components of the slider.
314
  final Color? activeColor;
315 316 317 318 319 320 321 322

  /// The color of the track's inactive segments, i.e. the span of tracks
  /// between the min and the start thumb, and the end thumb and the max.
  ///
  /// Defaults to [ColorScheme.primary] with 24% opacity.
  ///
  /// Using a [SliderTheme] gives more fine-grained control over the
  /// appearance of various components of the slider.
323
  final Color? inactiveColor;
324

325 326 327 328
  /// The highlight color that's typically used to indicate that
  /// the range slider thumb is hovered or dragged.
  ///
  /// If this property is null, [RangeSlider] will use [activeColor] with
329
  /// an opacity of 0.12. If null, [SliderThemeData.overlayColor]
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
  /// will be used, otherwise defaults to [ColorScheme.primary] with
  /// an opacity of 0.12.
  final MaterialStateProperty<Color?>? overlayColor;

  /// The cursor for a mouse pointer when it enters or is hovering over the
  /// widget.
  ///
  /// 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].
  final MaterialStateProperty<MouseCursor?>? mouseCursor;

345 346 347 348 349 350 351
  /// The callback used to create a semantic value from the slider's values.
  ///
  /// 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.
  ///
352
  /// {@tool snippet}
353 354 355 356 357 358 359 360 361 362 363 364 365 366
  ///
  /// In the example below, a slider for currency values is configured to
  /// announce a value with a currency label.
  ///
  /// ```dart
  /// RangeSlider(
  ///   values: _dollarsRange,
  ///   min: 20.0,
  ///   max: 330.0,
  ///   onChanged: (RangeValues newValues) {
  ///     setState(() {
  ///       _dollarsRange = newValues;
  ///     });
  ///   },
367 368
  ///   semanticFormatterCallback: (double newValue) {
  ///     return '${newValue.round()} dollars';
369 370 371 372
  ///   }
  ///  )
  /// ```
  /// {@end-tool}
373
  final SemanticFormatterCallback? semanticFormatterCallback;
374 375

  // Touch width for the tap boundary of the slider thumbs.
376
  static const double _minTouchTargetWidth = kMinInteractiveDimension;
377 378

  @override
379
  State<RangeSlider> createState() => _RangeSliderState();
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DoubleProperty('valueStart', values.start));
    properties.add(DoubleProperty('valueEnd', values.end));
    properties.add(ObjectFlagProperty<ValueChanged<RangeValues>>('onChanged', onChanged, ifNull: 'disabled'));
    properties.add(ObjectFlagProperty<ValueChanged<RangeValues>>.has('onChangeStart', onChangeStart));
    properties.add(ObjectFlagProperty<ValueChanged<RangeValues>>.has('onChangeEnd', onChangeEnd));
    properties.add(DoubleProperty('min', min));
    properties.add(DoubleProperty('max', max));
    properties.add(IntProperty('divisions', divisions));
    properties.add(StringProperty('labelStart', labels?.start));
    properties.add(StringProperty('labelEnd', labels?.end));
    properties.add(ColorProperty('activeColor', activeColor));
    properties.add(ColorProperty('inactiveColor', inactiveColor));
396
    properties.add(ObjectFlagProperty<ValueChanged<double>>.has('semanticFormatterCallback', semanticFormatterCallback));
397
  }
398 399 400 401 402 403 404 405
}

class _RangeSliderState extends State<RangeSlider> with TickerProviderStateMixin {
  static const Duration enableAnimationDuration = Duration(milliseconds: 75);
  static const Duration valueIndicatorAnimationDuration = Duration(milliseconds: 100);

  // Animation controller that is run when the overlay (a.k.a radial reaction)
  // changes visibility in response to user interaction.
406
  late AnimationController overlayController;
407 408

  // Animation controller that is run when the value indicators change visibility.
409
  late AnimationController valueIndicatorController;
410 411

  // Animation controller that is run when enabling/disabling the slider.
412
  late AnimationController enableController;
413 414 415

  // Animation controllers that are run when transitioning between one value
  // and the next on a discrete slider.
416 417 418
  late AnimationController startPositionController;
  late AnimationController endPositionController;
  Timer? interactionTimer;
419
  // Value Indicator paint Animation that appears on the Overlay.
420 421
  PaintRangeValueIndicator? paintTopValueIndicator;
  PaintRangeValueIndicator? paintBottomValueIndicator;
422

423 424 425 426 427 428 429 430 431 432
  bool get _enabled => widget.onChanged != null;

  bool _dragging = false;

  bool _hovering = false;
  void _handleHoverChanged(bool hovering) {
    if (hovering != _hovering) {
      setState(() { _hovering = hovering; });
    }
  }
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447

  @override
  void initState() {
    super.initState();
    overlayController = AnimationController(
      duration: kRadialReactionDuration,
      vsync: this,
    );
    valueIndicatorController = AnimationController(
      duration: valueIndicatorAnimationDuration,
      vsync: this,
    );
    enableController = AnimationController(
      duration: enableAnimationDuration,
      vsync: this,
448
      value: _enabled ? 1.0 : 0.0,
449 450 451 452
    );
    startPositionController = AnimationController(
      duration: Duration.zero,
      vsync: this,
453
      value: _unlerp(widget.values.start),
454 455 456 457
    );
    endPositionController = AnimationController(
      duration: Duration.zero,
      vsync: this,
458
      value: _unlerp(widget.values.end),
459 460 461 462 463 464
    );
  }

  @override
  void didUpdateWidget(RangeSlider oldWidget) {
    super.didUpdateWidget(oldWidget);
465
    if (oldWidget.onChanged == widget.onChanged) {
466
      return;
467
    }
468
    final bool wasEnabled = oldWidget.onChanged != null;
469
    final bool isEnabled = _enabled;
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    if (wasEnabled != isEnabled) {
      if (isEnabled) {
        enableController.forward();
      } else {
        enableController.reverse();
      }
    }
  }

  @override
  void dispose() {
    interactionTimer?.cancel();
    overlayController.dispose();
    valueIndicatorController.dispose();
    enableController.dispose();
    startPositionController.dispose();
    endPositionController.dispose();
487
    if (overlayEntry != null) {
488
      overlayEntry!.remove();
489 490
      overlayEntry = null;
    }
491 492 493 494
    super.dispose();
  }

  void _handleChanged(RangeValues values) {
495
    assert(_enabled);
496 497
    final RangeValues lerpValues = _lerpRangeValues(values);
    if (lerpValues != widget.values) {
498
      widget.onChanged!(lerpValues);
499 500 501 502 503
    }
  }

  void _handleDragStart(RangeValues values) {
    assert(widget.onChangeStart != null);
504
    _dragging = true;
505
    widget.onChangeStart!(_lerpRangeValues(values));
506 507 508 509
  }

  void _handleDragEnd(RangeValues values) {
    assert(widget.onChangeEnd != null);
510
    _dragging = false;
511
    widget.onChangeEnd!(_lerpRangeValues(values));
512 513 514 515
  }

  // Returns a number between min and max, proportional to value, which must
  // be between 0.0 and 1.0.
516
  double _lerp(double value) => ui.lerpDouble(widget.min, widget.max, value)!;
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535

  // Returns a new range value with the start and end lerped.
  RangeValues _lerpRangeValues(RangeValues values) {
    return RangeValues(_lerp(values.start), _lerp(values.end));
  }

  // 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);
    return widget.max > widget.min ? (value - widget.min) / (widget.max - widget.min) : 0.0;
  }

  // Returns a new range value with the start and end unlerped.
  RangeValues _unlerpRangeValues(RangeValues values) {
    return RangeValues(_unlerp(values.start), _unlerp(values.end));
  }

  // Finds closest thumb. If the thumbs are close to each other, no thumb is
536 537
  // immediately selected while the drag displacement is zero. If the first
  // non-zero displacement is negative, then the left thumb is selected, and if its
538
  // positive, then the right thumb is selected.
539
  Thumb? _defaultRangeThumbSelector(
540 541 542 543 544 545 546
    TextDirection textDirection,
    RangeValues values,
    double tapValue,
    Size thumbSize,
    Size trackSize,
    double dx, // The horizontal delta or displacement of the drag update.
  ) {
547 548 549 550
    final double touchRadius = math.max(thumbSize.width, RangeSlider._minTouchTargetWidth) / 2;
    final bool inStartTouchTarget = (tapValue - values.start).abs() * trackSize.width < touchRadius;
    final bool inEndTouchTarget = (tapValue - values.end).abs() * trackSize.width < touchRadius;

551 552 553 554 555
    // Use dx if the thumb touch targets overlap. If dx is 0 and the drag
    // position is in both touch targets, no thumb is selected because it is
    // ambiguous to which thumb should be selected. If the dx is non-zero, the
    // thumb selection is determined by the direction of the dx. The left thumb
    // is chosen for negative dx, and the right thumb is chosen for positive dx.
556
    if (inStartTouchTarget && inEndTouchTarget) {
557 558
      final bool towardsStart;
      final bool towardsEnd;
559 560 561 562 563 564 565 566 567 568
      switch (textDirection) {
        case TextDirection.ltr:
          towardsStart = dx < 0;
          towardsEnd = dx > 0;
          break;
        case TextDirection.rtl:
          towardsStart = dx > 0;
          towardsEnd = dx < 0;
          break;
      }
569
      if (towardsStart) {
570
        return Thumb.start;
571 572
      }
      if (towardsEnd) {
573
        return Thumb.end;
574
      }
575 576
    } else {
      // Snap position on the track if its in the inactive range.
577
      if (tapValue < values.start || inStartTouchTarget) {
578
        return Thumb.start;
579 580
      }
      if (tapValue > values.end || inEndTouchTarget) {
581
        return Thumb.end;
582
      }
583 584
    }
    return null;
585
  }
586 587 588 589 590 591

  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasMaterial(context));
    assert(debugCheckHasMediaQuery(context));

592
    final ThemeData theme = Theme.of(context);
593 594 595 596 597 598 599 600
    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
    // 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.
601

602 603 604 605 606 607 608 609
    const double defaultTrackHeight = 4;
    const RangeSliderTrackShape defaultTrackShape = RoundedRectRangeSliderTrackShape();
    const RangeSliderTickMarkShape defaultTickMarkShape = RoundRangeSliderTickMarkShape();
    const SliderComponentShape defaultOverlayShape = RoundSliderOverlayShape();
    const RangeSliderThumbShape defaultThumbShape = RoundRangeSliderThumbShape();
    const RangeSliderValueIndicatorShape defaultValueIndicatorShape = RectangularRangeSliderValueIndicatorShape();
    const ShowValueIndicator defaultShowValueIndicator = ShowValueIndicator.onlyForDiscrete;
    const double defaultMinThumbSeparation = 8;
610

611 612 613 614 615 616
    final Set<MaterialState> states = <MaterialState>{
      if (!_enabled) MaterialState.disabled,
      if (_hovering) MaterialState.hovered,
      if (_dragging) MaterialState.dragged,
    };

617 618 619 620
    // 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.
621
    final RangeSliderValueIndicatorShape valueIndicatorShape = sliderTheme.rangeValueIndicatorShape ?? defaultValueIndicatorShape;
622
    final Color valueIndicatorColor;
623 624 625 626 627 628
    if (valueIndicatorShape is RectangularRangeSliderValueIndicatorShape) {
      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;
    }

629 630 631 632 633 634 635
    Color? effectiveOverlayColor() {
      return widget.overlayColor?.resolve(states)
        ?? widget.activeColor?.withOpacity(0.12)
        ?? MaterialStateProperty.resolveAs<Color?>(sliderTheme.overlayColor, states)
        ?? theme.colorScheme.primary.withOpacity(0.12);
    }

636
    sliderTheme = sliderTheme.copyWith(
637
      trackHeight: sliderTheme.trackHeight ?? defaultTrackHeight,
638 639 640 641 642 643 644 645 646 647
      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),
      thumbColor: widget.activeColor ?? sliderTheme.thumbColor ?? theme.colorScheme.primary,
      overlappingShapeStrokeColor: sliderTheme.overlappingShapeStrokeColor ?? theme.colorScheme.surface,
648
      disabledThumbColor: sliderTheme.disabledThumbColor ?? Color.alphaBlend(theme.colorScheme.onSurface.withOpacity(.38), theme.colorScheme.surface),
649
      overlayColor: effectiveOverlayColor(),
650
      valueIndicatorColor: valueIndicatorColor,
651 652 653 654
      rangeTrackShape: sliderTheme.rangeTrackShape ?? defaultTrackShape,
      rangeTickMarkShape: sliderTheme.rangeTickMarkShape ?? defaultTickMarkShape,
      rangeThumbShape: sliderTheme.rangeThumbShape ?? defaultThumbShape,
      overlayShape: sliderTheme.overlayShape ?? defaultOverlayShape,
655
      rangeValueIndicatorShape: valueIndicatorShape,
656
      showValueIndicator: sliderTheme.showValueIndicator ?? defaultShowValueIndicator,
657
      valueIndicatorTextStyle: sliderTheme.valueIndicatorTextStyle ?? theme.textTheme.bodyLarge!.copyWith(
658 659
        color: theme.colorScheme.onPrimary,
      ),
660
      minThumbSeparation: sliderTheme.minThumbSeparation ?? defaultMinThumbSeparation,
661 662
      thumbSelector: sliderTheme.thumbSelector ?? _defaultRangeThumbSelector,
    );
663 664 665
    final MouseCursor effectiveMouseCursor = widget.mouseCursor?.resolve(states)
      ?? sliderTheme.mouseCursor?.resolve(states)
      ?? MaterialStateMouseCursor.clickable.resolve(states);
666

667 668 669
    // 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 slider.dart.
670
    Size screenSize() => MediaQuery.sizeOf(context);
671

672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
    return FocusableActionDetector(
      enabled: _enabled,
      onShowHoverHighlight: _handleHoverChanged,
      includeFocusSemantics: false,
      mouseCursor: effectiveMouseCursor,
      child: CompositedTransformTarget(
        link: _layerLink,
        child: _RangeSliderRenderObjectWidget(
          values: _unlerpRangeValues(widget.values),
          divisions: widget.divisions,
          labels: widget.labels,
          sliderTheme: sliderTheme,
          textScaleFactor: MediaQuery.of(context).textScaleFactor,
          screenSize: screenSize(),
          onChanged: _enabled && (widget.max > widget.min) ? _handleChanged : null,
          onChangeStart: widget.onChangeStart != null ? _handleDragStart : null,
          onChangeEnd: widget.onChangeEnd != null ? _handleDragEnd : null,
          state: this,
          semanticFormatterCallback: widget.semanticFormatterCallback,
          hovering: _hovering,
        ),
693
      ),
694 695
    );
  }
696 697 698

  final LayerLink _layerLink = LayerLink();

699
  OverlayEntry? overlayEntry;
700 701 702 703 704 705 706 707 708 709 710 711 712

  void showValueIndicator() {
    if (overlayEntry == null) {
      overlayEntry = OverlayEntry(
        builder: (BuildContext context) {
          return CompositedTransformFollower(
            link: _layerLink,
            child: _ValueIndicatorRenderObjectWidget(
              state: this,
            ),
          );
        },
      );
713
      Overlay.of(context, debugRequiredFor: widget).insert(overlayEntry!);
714 715
    }
  }
716 717 718 719
}

class _RangeSliderRenderObjectWidget extends LeafRenderObjectWidget {
  const _RangeSliderRenderObjectWidget({
720 721 722 723 724 725 726 727 728 729 730
    required this.values,
    required this.divisions,
    required this.labels,
    required this.sliderTheme,
    required this.textScaleFactor,
    required this.screenSize,
    required this.onChanged,
    required this.onChangeStart,
    required this.onChangeEnd,
    required this.state,
    required this.semanticFormatterCallback,
731
    required this.hovering,
732
  });
733 734

  final RangeValues values;
735 736
  final int? divisions;
  final RangeLabels? labels;
737 738
  final SliderThemeData sliderTheme;
  final double textScaleFactor;
739
  final Size screenSize;
740 741 742 743
  final ValueChanged<RangeValues>? onChanged;
  final ValueChanged<RangeValues>? onChangeStart;
  final ValueChanged<RangeValues>? onChangeEnd;
  final SemanticFormatterCallback? semanticFormatterCallback;
744
  final _RangeSliderState state;
745
  final bool hovering;
746 747 748 749 750 751 752 753 754 755

  @override
  _RenderRangeSlider createRenderObject(BuildContext context) {
    return _RenderRangeSlider(
      values: values,
      divisions: divisions,
      labels: labels,
      sliderTheme: sliderTheme,
      theme: Theme.of(context),
      textScaleFactor: textScaleFactor,
756
      screenSize: screenSize,
757 758 759 760
      onChanged: onChanged,
      onChangeStart: onChangeStart,
      onChangeEnd: onChangeEnd,
      state: state,
761
      textDirection: Directionality.of(context),
762
      semanticFormatterCallback: semanticFormatterCallback,
763
      platform: Theme.of(context).platform,
764
      hovering: hovering,
765
      gestureSettings: MediaQuery.gestureSettingsOf(context),
766 767 768 769 770 771
    );
  }

  @override
  void updateRenderObject(BuildContext context, _RenderRangeSlider renderObject) {
    renderObject
772 773
      // We should update the `divisions` ahead of `values`, because the `values`
      // setter dependent on the `divisions`.
774
      ..divisions = divisions
775
      ..values = values
776 777 778 779
      ..labels = labels
      ..sliderTheme = sliderTheme
      ..theme = Theme.of(context)
      ..textScaleFactor = textScaleFactor
780
      ..screenSize = screenSize
781 782 783
      ..onChanged = onChanged
      ..onChangeStart = onChangeStart
      ..onChangeEnd = onChangeEnd
784
      ..textDirection = Directionality.of(context)
785
      ..semanticFormatterCallback = semanticFormatterCallback
786
      ..platform = Theme.of(context).platform
787
      ..hovering = hovering
788
      ..gestureSettings = MediaQuery.gestureSettingsOf(context);
789 790 791
  }
}

792
class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
793
  _RenderRangeSlider({
794 795 796 797 798 799 800 801 802 803 804 805 806 807
    required RangeValues values,
    required int? divisions,
    required RangeLabels? labels,
    required SliderThemeData sliderTheme,
    required ThemeData? theme,
    required double textScaleFactor,
    required Size screenSize,
    required TargetPlatform platform,
    required ValueChanged<RangeValues>? onChanged,
    required SemanticFormatterCallback? semanticFormatterCallback,
    required this.onChangeStart,
    required this.onChangeEnd,
    required _RangeSliderState state,
    required TextDirection textDirection,
808
    required bool hovering,
809
    required DeviceGestureSettings gestureSettings,
810
  })  : assert(values.start >= 0.0 && values.start <= 1.0),
811 812 813 814 815 816 817 818 819
        assert(values.end >= 0.0 && values.end <= 1.0),
        _platform = platform,
        _semanticFormatterCallback = semanticFormatterCallback,
        _labels = labels,
        _values = values,
        _divisions = divisions,
        _sliderTheme = sliderTheme,
        _theme = theme,
        _textScaleFactor = textScaleFactor,
820
        _screenSize = screenSize,
821 822
        _onChanged = onChanged,
        _state = state,
823 824
        _textDirection = textDirection,
        _hovering = hovering {
825 826 827 828 829 830 831
    _updateLabelPainters();
    final GestureArenaTeam team = GestureArenaTeam();
    _drag = HorizontalDragGestureRecognizer()
      ..team = team
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
      ..onEnd = _handleDragEnd
832 833
      ..onCancel = _handleDragCancel
      ..gestureSettings = gestureSettings;
834 835 836 837
    _tap = TapGestureRecognizer()
      ..team = team
      ..onTapDown = _handleTapDown
      ..onTapUp = _handleTapUp
838 839
      ..onTapCancel = _handleTapCancel
      ..gestureSettings = gestureSettings;
840 841 842 843 844 845 846
    _overlayAnimation = CurvedAnimation(
      parent: _state.overlayController,
      curve: Curves.fastOutSlowIn,
    );
    _valueIndicatorAnimation = CurvedAnimation(
      parent: _state.valueIndicatorController,
      curve: Curves.fastOutSlowIn,
847 848
    )..addStatusListener((AnimationStatus status) {
      if (status == AnimationStatus.dismissed && _state.overlayEntry != null) {
849
        _state.overlayEntry!.remove();
850 851 852
        _state.overlayEntry = null;
      }
    });
853 854 855 856 857 858 859 860
    _enableAnimation = CurvedAnimation(
      parent: _state.enableController,
      curve: Curves.easeInOut,
    );
  }

  // Keep track of the last selected thumb so they can be drawn in the
  // right order.
861
  Thumb? _lastThumbSelection;
862 863 864 865 866 867 868 869 870 871 872 873

  static const Duration _positionAnimationDuration = Duration(milliseconds: 75);

  // 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);
  double get _maxSliderPartHeight => _sliderPartSizes.map((Size size) => size.height).reduce(math.max);
  List<Size> get _sliderPartSizes => <Size>[
874 875 876
    _sliderTheme.overlayShape!.getPreferredSize(isEnabled, isDiscrete),
    _sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete),
    _sliderTheme.rangeTickMarkShape!.getPreferredSize(isEnabled: isEnabled, sliderTheme: sliderTheme),
877
  ];
878
  double? get _minPreferredTrackHeight => _sliderTheme.trackHeight;
879 880 881 882

  // 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).
883
  Rect get _trackRect => _sliderTheme.rangeTrackShape!.getPreferredRect(
884 885 886 887 888 889 890
    parentBox: this,
    sliderTheme: _sliderTheme,
    isDiscrete: false,
  );

  static const Duration _minimumInteractionTime = Duration(milliseconds: 500);

891
  final _RangeSliderState _state;
892 893 894
  late Animation<double> _overlayAnimation;
  late Animation<double> _valueIndicatorAnimation;
  late Animation<double> _enableAnimation;
895 896
  final TextPainter _startLabelPainter = TextPainter();
  final TextPainter _endLabelPainter = TextPainter();
897 898
  late HorizontalDragGestureRecognizer _drag;
  late TapGestureRecognizer _tap;
899
  bool _active = false;
900
  late RangeValues _newValues;
901 902
  late Offset _startThumbCenter;
  late Offset _endThumbCenter;
903 904
  Rect? overlayStartRect;
  Rect? overlayEndRect;
905 906 907

  bool get isEnabled => onChanged != null;

908
  bool get isDiscrete => divisions != null && divisions! > 0;
909

910
  double get _minThumbSeparationValue => isDiscrete ? 0 : sliderTheme.minThumbSeparation! / _trackRect.width;
911

912 913 914
  RangeValues get values => _values;
  RangeValues _values;
  set values(RangeValues newValues) {
915 916
    assert(newValues.start >= 0.0 && newValues.start <= 1.0);
    assert(newValues.end >= 0.0 && newValues.end <= 1.0);
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
    assert(newValues.start <= newValues.end);
    final RangeValues convertedValues = isDiscrete ? _discretizeRangeValues(newValues) : newValues;
    if (convertedValues == _values) {
      return;
    }
    _values = convertedValues;
    if (isDiscrete) {
      // 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 startDistance = (_values.start -  _state.startPositionController.value).abs();
      _state.startPositionController.duration = startDistance != 0.0 ? _positionAnimationDuration * (1.0 / startDistance) : Duration.zero;
      _state.startPositionController.animateTo(_values.start, curve: Curves.easeInOut);
      final double endDistance = (_values.end -  _state.endPositionController.value).abs();
      _state.endPositionController.duration = endDistance != 0.0 ? _positionAnimationDuration * (1.0 / endDistance) : Duration.zero;
      _state.endPositionController.animateTo(_values.end, curve: Curves.easeInOut);
    } else {
      _state.startPositionController.value = convertedValues.start;
      _state.endPositionController.value = convertedValues.end;
    }
    markNeedsSemanticsUpdate();
  }

  TargetPlatform _platform;
  TargetPlatform get platform => _platform;
  set platform(TargetPlatform value) {
944
    if (_platform == value) {
945
      return;
946
    }
947 948 949 950
    _platform = value;
    markNeedsSemanticsUpdate();
  }

951 952 953 954 955 956
  DeviceGestureSettings? get gestureSettings => _drag.gestureSettings;
  set gestureSettings(DeviceGestureSettings? gestureSettings) {
    _drag.gestureSettings = gestureSettings;
    _tap.gestureSettings = gestureSettings;
  }

957 958 959
  SemanticFormatterCallback? _semanticFormatterCallback;
  SemanticFormatterCallback? get semanticFormatterCallback => _semanticFormatterCallback;
  set semanticFormatterCallback(SemanticFormatterCallback? value) {
960
    if (_semanticFormatterCallback == value) {
961
      return;
962
    }
963 964 965 966
    _semanticFormatterCallback = value;
    markNeedsSemanticsUpdate();
  }

967 968 969
  int? get divisions => _divisions;
  int? _divisions;
  set divisions(int? value) {
970 971 972 973 974 975 976
    if (value == _divisions) {
      return;
    }
    _divisions = value;
    markNeedsPaint();
  }

977 978 979
  RangeLabels? get labels => _labels;
  RangeLabels? _labels;
  set labels(RangeLabels? labels) {
980
    if (labels == _labels) {
981
      return;
982
    }
983 984 985 986 987 988 989
    _labels = labels;
    _updateLabelPainters();
  }

  SliderThemeData get sliderTheme => _sliderTheme;
  SliderThemeData _sliderTheme;
  set sliderTheme(SliderThemeData value) {
990
    if (value == _sliderTheme) {
991
      return;
992
    }
993 994 995 996
    _sliderTheme = value;
    markNeedsPaint();
  }

997 998 999
  ThemeData? get theme => _theme;
  ThemeData? _theme;
  set theme(ThemeData? value) {
1000
    if (value == _theme) {
1001
      return;
1002
    }
1003 1004 1005 1006 1007 1008 1009
    _theme = value;
    markNeedsPaint();
  }

  double get textScaleFactor => _textScaleFactor;
  double _textScaleFactor;
  set textScaleFactor(double value) {
1010
    if (value == _textScaleFactor) {
1011
      return;
1012
    }
1013 1014 1015 1016
    _textScaleFactor = value;
    _updateLabelPainters();
  }

1017 1018 1019
  Size get screenSize => _screenSize;
  Size _screenSize;
  set screenSize(Size value) {
1020
    if (value == screenSize) {
1021
      return;
1022
    }
1023 1024 1025 1026
    _screenSize = value;
    markNeedsPaint();
  }

1027 1028 1029
  ValueChanged<RangeValues>? get onChanged => _onChanged;
  ValueChanged<RangeValues>? _onChanged;
  set onChanged(ValueChanged<RangeValues>? value) {
1030
    if (value == _onChanged) {
1031
      return;
1032
    }
1033 1034 1035 1036 1037 1038 1039 1040
    final bool wasEnabled = isEnabled;
    _onChanged = value;
    if (wasEnabled != isEnabled) {
      markNeedsPaint();
      markNeedsSemanticsUpdate();
    }
  }

1041 1042
  ValueChanged<RangeValues>? onChangeStart;
  ValueChanged<RangeValues>? onChangeEnd;
1043 1044 1045 1046

  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
1047
    if (value == _textDirection) {
1048
      return;
1049
    }
1050 1051 1052 1053
    _textDirection = value;
    _updateLabelPainters();
  }

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
  /// True if this slider is being hovered over by a pointer.
  bool get hovering => _hovering;
  bool _hovering;
  set hovering(bool value) {
    if (value == _hovering) {
      return;
    }
    _hovering = value;
    _updateForHover(_hovering);
  }

  /// True if the slider is interactive and the start thumb is being
  /// hovered over by a pointer.
  bool _hoveringStartThumb = false;
  bool get hoveringStartThumb => _hoveringStartThumb;
  set hoveringStartThumb(bool value) {
    if (value == _hoveringStartThumb) {
      return;
    }
    _hoveringStartThumb = value;
    _updateForHover(_hovering);
  }

  /// True if the slider is interactive and the end thumb is being
  /// hovered over by a pointer.
  bool _hoveringEndThumb = false;
  bool get hoveringEndThumb => _hoveringEndThumb;
  set hoveringEndThumb(bool value) {
    if (value == _hoveringEndThumb) {
      return;
    }
    _hoveringEndThumb = value;
    _updateForHover(_hovering);
  }

  void _updateForHover(bool hovered) {
    // Only show overlay when pointer is hovering the thumb.
    if (hovered && (hoveringStartThumb || hoveringEndThumb)) {
      _state.overlayController.forward();
    } else {
      _state.overlayController.reverse();
    }
  }

1098
  bool get showValueIndicator {
1099
    switch (_sliderTheme.showValueIndicator!) {
1100
      case ShowValueIndicator.onlyForDiscrete:
1101
        return isDiscrete;
1102
      case ShowValueIndicator.onlyForContinuous:
1103
        return !isDiscrete;
1104
      case ShowValueIndicator.always:
1105
        return true;
1106
      case ShowValueIndicator.never:
1107
        return false;
1108 1109 1110
    }
  }

1111
  Size get _thumbSize => _sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete);
1112 1113 1114 1115 1116 1117 1118 1119

  double get _adjustmentUnit {
    switch (_platform) {
      case TargetPlatform.iOS:
        // Matches iOS implementation of material slider.
        return 0.1;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
1120 1121 1122
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
        // Matches Android implementation of material slider.
        return 0.05;
    }
  }

  void _updateLabelPainters() {
    _updateLabelPainter(Thumb.start);
    _updateLabelPainter(Thumb.end);
  }

  void _updateLabelPainter(Thumb thumb) {
1134
    if (labels == null) {
1135
      return;
1136
    }
1137

1138 1139
    final String text;
    final TextPainter labelPainter;
1140 1141
    switch (thumb) {
      case Thumb.start:
1142
        text = labels!.start;
1143 1144 1145
        labelPainter = _startLabelPainter;
        break;
      case Thumb.end:
1146
        text = labels!.end;
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
        labelPainter = _endLabelPainter;
        break;
    }

    if (labels != null) {
      labelPainter
        ..text = TextSpan(
          style: _sliderTheme.valueIndicatorTextStyle,
          text: text,
        )
        ..textDirection = textDirection
        ..textScaleFactor = textScaleFactor
        ..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();
  }

1169 1170 1171 1172 1173 1174 1175 1176
  @override
  void systemFontsDidChange() {
    super.systemFontsDidChange();
    _startLabelPainter.markNeedsLayout();
    _endLabelPainter.markNeedsLayout();
    _updateLabelPainters();
  }

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    _overlayAnimation.addListener(markNeedsPaint);
    _valueIndicatorAnimation.addListener(markNeedsPaint);
    _enableAnimation.addListener(markNeedsPaint);
    _state.startPositionController.addListener(markNeedsPaint);
    _state.endPositionController.addListener(markNeedsPaint);
  }

  @override
  void detach() {
    _overlayAnimation.removeListener(markNeedsPaint);
    _valueIndicatorAnimation.removeListener(markNeedsPaint);
    _enableAnimation.removeListener(markNeedsPaint);
    _state.startPositionController.removeListener(markNeedsPaint);
    _state.endPositionController.removeListener(markNeedsPaint);
    super.detach();
  }

1197 1198 1199 1200 1201 1202 1203
  @override
  void dispose() {
    _startLabelPainter.dispose();
    _endLabelPainter.dispose();
    super.dispose();
  }

1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
  double _getValueFromVisualPosition(double visualPosition) {
    switch (textDirection) {
      case TextDirection.rtl:
        return 1.0 - visualPosition;
      case TextDirection.ltr:
        return visualPosition;
    }
  }

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

  double _discretize(double value) {
1219
    double result = clampDouble(value, 0.0, 1.0);
1220
    if (isDiscrete) {
1221
      result = (result * divisions!).round() / divisions!;
1222 1223 1224 1225 1226 1227 1228 1229 1230
    }
    return result;
  }

  RangeValues _discretizeRangeValues(RangeValues values) {
    return RangeValues(_discretize(values.start), _discretize(values.end));
  }

  void _startInteraction(Offset globalPosition) {
1231
    _state.showValueIndicator();
1232
    final double tapValue = clampDouble(_getValueFromGlobalPosition(globalPosition), 0.0, 1.0);
1233
    _lastThumbSelection = sliderTheme.thumbSelector!(textDirection, values, tapValue, _thumbSize, size, 0);
1234 1235 1236 1237 1238 1239 1240 1241

    if (_lastThumbSelection != null) {
      _active = true;
      // We supply the *current* values as the start locations, 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.
      final RangeValues currentValues = _discretizeRangeValues(values);
      if (_lastThumbSelection == Thumb.start) {
1242
        _newValues = RangeValues(tapValue, currentValues.end);
1243
      } else if (_lastThumbSelection == Thumb.end) {
1244
        _newValues = RangeValues(currentValues.start, tapValue);
1245
      }
1246
      _updateLabelPainter(_lastThumbSelection!);
1247

1248
      onChangeStart?.call(currentValues);
1249

1250
      onChanged!(_discretizeRangeValues(_newValues));
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267

      _state.overlayController.forward();
      if (showValueIndicator) {
        _state.valueIndicatorController.forward();
        _state.interactionTimer?.cancel();
        _state.interactionTimer =
          Timer(_minimumInteractionTime * timeDilation, () {
            _state.interactionTimer = null;
            if (!_active && _state.valueIndicatorController.status == AnimationStatus.completed) {
              _state.valueIndicatorController.reverse();
            }
          });
      }
    }
  }

  void _handleDragUpdate(DragUpdateDetails details) {
1268 1269 1270 1271
    if (!_state.mounted) {
      return;
    }

1272 1273
    final double dragValue = _getValueFromGlobalPosition(details.globalPosition);

1274 1275 1276 1277
    // If no selection has been made yet, test for thumb selection again now
    // that the value of dx can be non-zero. If this is the first selection of
    // the interaction, then onChangeStart must be called.
    bool shouldCallOnChangeStart = false;
1278
    if (_lastThumbSelection == null) {
1279
      _lastThumbSelection = sliderTheme.thumbSelector!(textDirection, values, dragValue, _thumbSize, size, details.delta.dx);
1280
      if (_lastThumbSelection != null) {
1281 1282
        shouldCallOnChangeStart = true;
        _active = true;
1283 1284 1285 1286 1287 1288 1289 1290 1291
        _state.overlayController.forward();
        if (showValueIndicator) {
          _state.valueIndicatorController.forward();
        }
      }
    }

    if (isEnabled && _lastThumbSelection != null) {
      final RangeValues currentValues = _discretizeRangeValues(values);
1292
      if (onChangeStart != null && shouldCallOnChangeStart) {
1293
        onChangeStart!(currentValues);
1294
      }
1295 1296 1297
      final double currentDragValue = _discretize(dragValue);

      if (_lastThumbSelection == Thumb.start) {
1298
        _newValues = RangeValues(math.min(currentDragValue, currentValues.end - _minThumbSeparationValue), currentValues.end);
1299
      } else if (_lastThumbSelection == Thumb.end) {
1300
        _newValues = RangeValues(currentValues.start, math.max(currentDragValue, currentValues.start + _minThumbSeparationValue));
1301
      }
1302
      onChanged!(_newValues);
1303 1304 1305 1306
    }
  }

  void _endInteraction() {
1307 1308 1309 1310
    if (!_state.mounted) {
      return;
    }

1311 1312 1313 1314
    if (showValueIndicator && _state.interactionTimer == null) {
      _state.valueIndicatorController.reverse();
    }

1315 1316
    if (_active && _state.mounted && _lastThumbSelection != null) {
      final RangeValues discreteValues = _discretizeRangeValues(_newValues);
1317
      onChangeEnd?.call(discreteValues);
1318 1319
      _active = false;
    }
1320
    _state.overlayController.reverse();
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
  }

  void _handleDragStart(DragStartDetails details) {
    _startInteraction(details.globalPosition);
  }

  void _handleDragEnd(DragEndDetails details) {
    _endInteraction();
  }

  void _handleDragCancel() {
    _endInteraction();
  }

  void _handleTapDown(TapDownDetails details) {
    _startInteraction(details.globalPosition);
  }

  void _handleTapUp(TapUpDetails details) {
    _endInteraction();
  }

  void _handleTapCancel() {
    _endInteraction();
  }

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

  @override
  void handleEvent(PointerEvent event, HitTestEntry entry) {
    assert(debugHandleEvent(event, entry));
    if (event is PointerDownEvent && isEnabled) {
      // We need to add the drag first so that it has priority.
      _drag.addPointer(event);
      _tap.addPointer(event);
    }
1358 1359 1360 1361 1362 1363 1364 1365
    if (isEnabled) {
      if (overlayStartRect != null) {
        hoveringStartThumb = overlayStartRect!.contains(event.localPosition);
      }
      if (overlayEndRect != null) {
        hoveringEndThumb = overlayEndRect!.contains(event.localPosition);
      }
    }
1366 1367 1368 1369 1370 1371 1372 1373 1374
  }

  @override
  double computeMinIntrinsicWidth(double height) => _minPreferredTrackWidth + _maxSliderPartWidth;

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

  @override
1375
  double computeMinIntrinsicHeight(double width) => math.max(_minPreferredTrackHeight!, _maxSliderPartHeight);
1376 1377

  @override
1378
  double computeMaxIntrinsicHeight(double width) => math.max(_minPreferredTrackHeight!, _maxSliderPartHeight);
1379 1380 1381 1382 1383

  @override
  bool get sizedByParent => true;

  @override
1384 1385
  Size computeDryLayout(BoxConstraints constraints) {
    return Size(
1386
      constraints.hasBoundedWidth ? constraints.maxWidth : _minPreferredTrackWidth + _maxSliderPartWidth,
1387
      constraints.hasBoundedHeight ? constraints.maxHeight : math.max(_minPreferredTrackHeight!, _maxSliderPartHeight),
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
    );
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    final double startValue = _state.startPositionController.value;
    final double endValue = _state.endPositionController.value;

    // 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.
1399 1400
    final double startVisualPosition;
    final double endVisualPosition;
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
    switch (textDirection) {
      case TextDirection.rtl:
        startVisualPosition = 1.0 - startValue;
        endVisualPosition = 1.0 - endValue;
        break;
      case TextDirection.ltr:
        startVisualPosition = startValue;
        endVisualPosition = endValue;
        break;
    }

1412
    final Rect trackRect = _sliderTheme.rangeTrackShape!.getPreferredRect(
1413 1414 1415
        parentBox: this,
        offset: offset,
        sliderTheme: _sliderTheme,
1416
        isDiscrete: isDiscrete,
1417
    );
1418 1419
    _startThumbCenter = Offset(trackRect.left + startVisualPosition * trackRect.width, trackRect.center.dy);
    _endThumbCenter = Offset(trackRect.left + endVisualPosition * trackRect.width, trackRect.center.dy);
1420 1421 1422 1423 1424
    if (isEnabled) {
      final Size overlaySize = sliderTheme.overlayShape!.getPreferredSize(isEnabled, false);
      overlayStartRect = Rect.fromCircle(center: _startThumbCenter, radius: overlaySize.width / 2.0);
      overlayEndRect = Rect.fromCircle(center: _endThumbCenter, radius: overlaySize.width / 2.0);
    }
1425

1426
    _sliderTheme.rangeTrackShape!.paint(
1427 1428 1429 1430 1431 1432
        context,
        offset,
        parentBox: this,
        sliderTheme: _sliderTheme,
        enableAnimation: _enableAnimation,
        textDirection: _textDirection,
1433 1434
        startThumbCenter: _startThumbCenter,
        endThumbCenter: _endThumbCenter,
1435
        isDiscrete: isDiscrete,
1436
        isEnabled: isEnabled,
1437 1438
    );

1439 1440
    final bool startThumbSelected = _lastThumbSelection == Thumb.start;
    final bool endThumbSelected = _lastThumbSelection == Thumb.end;
1441
    final Size resolvedscreenSize = screenSize.isEmpty ? size : screenSize;
1442

1443
    if (!_overlayAnimation.isDismissed) {
1444
      if (startThumbSelected || hoveringStartThumb) {
1445
        _sliderTheme.overlayShape!.paint(
1446
          context,
1447
          _startThumbCenter,
1448 1449 1450 1451 1452 1453 1454 1455
          activationAnimation: _overlayAnimation,
          enableAnimation: _enableAnimation,
          isDiscrete: isDiscrete,
          labelPainter: _startLabelPainter,
          parentBox: this,
          sliderTheme: _sliderTheme,
          textDirection: _textDirection,
          value: startValue,
1456 1457
          textScaleFactor: _textScaleFactor,
          sizeWithOverflow: resolvedscreenSize,
1458 1459
        );
      }
1460
      if (endThumbSelected || hoveringEndThumb) {
1461
        _sliderTheme.overlayShape!.paint(
1462
          context,
1463
          _endThumbCenter,
1464 1465 1466 1467 1468 1469 1470 1471
          activationAnimation: _overlayAnimation,
          enableAnimation: _enableAnimation,
          isDiscrete: isDiscrete,
          labelPainter: _endLabelPainter,
          parentBox: this,
          sliderTheme: _sliderTheme,
          textDirection: _textDirection,
          value: endValue,
1472 1473
          textScaleFactor: _textScaleFactor,
          sizeWithOverflow: resolvedscreenSize,
1474 1475 1476 1477 1478
        );
      }
    }

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

1509
    final double thumbDelta = (_endThumbCenter.dx - _startThumbCenter.dx).abs();
1510 1511 1512

    final bool isLastThumbStart = _lastThumbSelection == Thumb.start;
    final Thumb bottomThumb = isLastThumbStart ? Thumb.end : Thumb.start;
1513
    final Thumb topThumb = isLastThumbStart ? Thumb.start : Thumb.end;
1514 1515
    final Offset bottomThumbCenter = isLastThumbStart ? _endThumbCenter : _startThumbCenter;
    final Offset topThumbCenter = isLastThumbStart ? _startThumbCenter : _endThumbCenter;
1516 1517 1518 1519
    final TextPainter bottomLabelPainter = isLastThumbStart ? _endLabelPainter : _startLabelPainter;
    final TextPainter topLabelPainter = isLastThumbStart ? _startLabelPainter : _endLabelPainter;
    final double bottomValue = isLastThumbStart ? endValue : startValue;
    final double topValue = isLastThumbStart ? startValue : endValue;
1520
    final bool shouldPaintValueIndicators = isEnabled && labels != null && !_valueIndicatorAnimation.isDismissed && showValueIndicator;
1521

1522
    if (shouldPaintValueIndicators) {
1523
      _state.paintBottomValueIndicator = (PaintingContext context, Offset offset) {
1524
        if (attached) {
1525
          _sliderTheme.rangeValueIndicatorShape!.paint(
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
            context,
            bottomThumbCenter,
            activationAnimation: _valueIndicatorAnimation,
            enableAnimation: _enableAnimation,
            isDiscrete: isDiscrete,
            isOnTop: false,
            labelPainter: bottomLabelPainter,
            parentBox: this,
            sliderTheme: _sliderTheme,
            textDirection: _textDirection,
            thumb: bottomThumb,
            value: bottomValue,
            textScaleFactor: textScaleFactor,
            sizeWithOverflow: resolvedscreenSize,
          );
        }
1542
      };
1543 1544
    }

1545
    _sliderTheme.rangeThumbShape!.paint(
1546 1547 1548 1549 1550 1551 1552 1553 1554
      context,
      bottomThumbCenter,
      activationAnimation: _valueIndicatorAnimation,
      enableAnimation: _enableAnimation,
      isDiscrete: isDiscrete,
      isOnTop: false,
      textDirection: textDirection,
      sliderTheme: _sliderTheme,
      thumb: bottomThumb,
1555
      isPressed: bottomThumb == Thumb.start ? startThumbSelected : endThumbSelected,
1556 1557 1558
    );

    if (shouldPaintValueIndicators) {
1559
      final double startOffset = sliderTheme.rangeValueIndicatorShape!.getHorizontalShift(
1560
        parentBox: this,
1561
        center: _startThumbCenter,
1562 1563
        labelPainter: _startLabelPainter,
        activationAnimation: _valueIndicatorAnimation,
1564 1565
        textScaleFactor: textScaleFactor,
        sizeWithOverflow: resolvedscreenSize,
1566
      );
1567
      final double endOffset = sliderTheme.rangeValueIndicatorShape!.getHorizontalShift(
1568
        parentBox: this,
1569
        center: _endThumbCenter,
1570 1571
        labelPainter: _endLabelPainter,
        activationAnimation: _valueIndicatorAnimation,
1572 1573
        textScaleFactor: textScaleFactor,
        sizeWithOverflow: resolvedscreenSize,
1574
      );
1575
      final double startHalfWidth = sliderTheme.rangeValueIndicatorShape!.getPreferredSize(
1576 1577 1578 1579 1580
        isEnabled,
        isDiscrete,
        labelPainter: _startLabelPainter,
        textScaleFactor: textScaleFactor,
      ).width / 2;
1581
      final double endHalfWidth = sliderTheme.rangeValueIndicatorShape!.getPreferredSize(
1582 1583 1584 1585 1586
        isEnabled,
        isDiscrete,
        labelPainter: _endLabelPainter,
        textScaleFactor: textScaleFactor,
      ).width / 2;
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
      double innerOverflow = startHalfWidth + endHalfWidth;
      switch (textDirection) {
        case TextDirection.ltr:
          innerOverflow += startOffset;
          innerOverflow -= endOffset;
          break;
        case TextDirection.rtl:
          innerOverflow -= startOffset;
          innerOverflow += endOffset;
          break;
      }

1599
      _state.paintTopValueIndicator = (PaintingContext context, Offset offset) {
1600
        if (attached) {
1601
          _sliderTheme.rangeValueIndicatorShape!.paint(
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
            context,
            topThumbCenter,
            activationAnimation: _valueIndicatorAnimation,
            enableAnimation: _enableAnimation,
            isDiscrete: isDiscrete,
            isOnTop: thumbDelta < innerOverflow,
            labelPainter: topLabelPainter,
            parentBox: this,
            sliderTheme: _sliderTheme,
            textDirection: _textDirection,
            thumb: topThumb,
            value: topValue,
            textScaleFactor: textScaleFactor,
            sizeWithOverflow: resolvedscreenSize,
          );
        }
1618
      };
1619 1620
    }

1621
    _sliderTheme.rangeThumbShape!.paint(
1622 1623
      context,
      topThumbCenter,
1624
      activationAnimation: _overlayAnimation,
1625 1626
      enableAnimation: _enableAnimation,
      isDiscrete: isDiscrete,
1627
      isOnTop: thumbDelta < sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete).width,
1628
      textDirection: textDirection,
1629
      sliderTheme: _sliderTheme,
1630
      thumb: topThumb,
1631
      isPressed: topThumb == Thumb.start ? startThumbSelected : endThumbSelected,
1632 1633 1634
    );
  }

1635
  /// Describe the semantics of the start thumb.
1636
  SemanticsNode? _startSemanticsNode = SemanticsNode();
1637 1638

  /// Describe the semantics of the end thumb.
1639
  SemanticsNode? _endSemanticsNode = SemanticsNode();
1640

1641 1642
  // Create the semantics configuration for a single value.
  SemanticsConfiguration _createSemanticsConfiguration(
1643 1644 1645 1646 1647
    double value,
    double increasedValue,
    double decreasedValue,
    VoidCallback increaseAction,
    VoidCallback decreaseAction,
1648 1649 1650 1651
  ) {
    final SemanticsConfiguration config = SemanticsConfiguration();
    config.isEnabled = isEnabled;
    config.textDirection = textDirection;
1652
    config.isSlider = true;
1653
    if (isEnabled) {
1654 1655 1656
      config.onIncrease = increaseAction;
      config.onDecrease = decreaseAction;
    }
1657

1658
    if (semanticFormatterCallback != null) {
1659 1660 1661
      config.value = semanticFormatterCallback!(_state._lerp(value));
      config.increasedValue = semanticFormatterCallback!(_state._lerp(increasedValue));
      config.decreasedValue = semanticFormatterCallback!(_state._lerp(decreasedValue));
1662 1663 1664 1665
    } else {
      config.value = '${(value * 100).round()}%';
      config.increasedValue = '${(increasedValue * 100).round()}%';
      config.decreasedValue = '${(decreasedValue * 100).round()}%';
1666
    }
1667 1668

    return config;
1669 1670
  }

1671 1672
  @override
  void assembleSemanticsNode(
1673 1674 1675
    SemanticsNode node,
    SemanticsConfiguration config,
    Iterable<SemanticsNode> children,
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
  ) {
    assert(children.isEmpty);

    final SemanticsConfiguration startSemanticsConfiguration = _createSemanticsConfiguration(
      values.start,
      _increasedStartValue,
      _decreasedStartValue,
      _increaseStartAction,
      _decreaseStartAction,
    );
    final SemanticsConfiguration endSemanticsConfiguration = _createSemanticsConfiguration(
      values.end,
      _increasedEndValue,
      _decreasedEndValue,
      _increaseEndAction,
      _decreaseEndAction,
    );

    // Split the semantics node area between the start and end nodes.
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
    final Rect leftRect = Rect.fromCenter(
      center: _startThumbCenter,
      width: kMinInteractiveDimension,
      height: kMinInteractiveDimension,
    );
    final Rect rightRect = Rect.fromCenter(
      center: _endThumbCenter,
      width: kMinInteractiveDimension,
      height: kMinInteractiveDimension,
    );
1705 1706
    switch (textDirection) {
      case TextDirection.ltr:
1707 1708
        _startSemanticsNode!.rect = leftRect;
        _endSemanticsNode!.rect = rightRect;
1709 1710
        break;
      case TextDirection.rtl:
1711 1712
        _startSemanticsNode!.rect = rightRect;
        _endSemanticsNode!.rect = leftRect;
1713 1714 1715
        break;
    }

1716 1717
    _startSemanticsNode!.updateWith(config: startSemanticsConfiguration);
    _endSemanticsNode!.updateWith(config: endSemanticsConfiguration);
1718 1719

    final List<SemanticsNode> finalChildren = <SemanticsNode>[
1720 1721
      _startSemanticsNode!,
      _endSemanticsNode!,
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
    ];

    node.updateWith(config: config, childrenInInversePaintOrder: finalChildren);
  }

  @override
  void clearSemantics() {
    super.clearSemantics();
    _startSemanticsNode = null;
    _endSemanticsNode = null;
  }

  @override
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
    config.isSemanticBoundary = true;
  }
1739

1740
  double get _semanticActionUnit => divisions != null ? 1.0 / divisions! : _adjustmentUnit;
1741 1742 1743

  void _increaseStartAction() {
    if (isEnabled) {
1744
      onChanged!(RangeValues(_increasedStartValue, values.end));
1745 1746 1747 1748 1749
    }
  }

  void _decreaseStartAction() {
    if (isEnabled) {
1750
      onChanged!(RangeValues(_decreasedStartValue, values.end));
1751 1752 1753 1754 1755
    }
  }

  void _increaseEndAction() {
    if (isEnabled) {
1756
      onChanged!(RangeValues(values.start, _increasedEndValue));
1757 1758 1759 1760 1761
    }
  }

  void _decreaseEndAction() {
    if (isEnabled) {
1762
      onChanged!(RangeValues(values.start, _decreasedEndValue));
1763 1764 1765
    }
  }

1766 1767 1768 1769 1770 1771 1772 1773
  double get _increasedStartValue {
    // Due to floating-point operations, this value can actually be greater than
    // expected (e.g. 0.4 + 0.2 = 0.600000000001), so we limit to 2 decimal points.
    final double increasedStartValue = double.parse((values.start + _semanticActionUnit).toStringAsFixed(2));
    return increasedStartValue <= values.end - _minThumbSeparationValue ? increasedStartValue : values.start;
  }

  double get _decreasedStartValue {
1774
    return clampDouble(values.start - _semanticActionUnit, 0.0, 1.0);
1775 1776 1777
  }

  double get _increasedEndValue {
1778
    return clampDouble(values.end + _semanticActionUnit, 0.0, 1.0);
1779 1780
  }

1781 1782 1783
  double get _decreasedEndValue {
    final double decreasedEndValue = values.end - _semanticActionUnit;
    return decreasedEndValue >= values.start + _minThumbSeparationValue ? decreasedEndValue : values.end;
1784
  }
1785
}
1786 1787 1788 1789


class _ValueIndicatorRenderObjectWidget extends LeafRenderObjectWidget {
  const _ValueIndicatorRenderObjectWidget({
1790
    required this.state,
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
  });

  final _RangeSliderState 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({
1809
    required _RangeSliderState state,
1810 1811 1812 1813 1814 1815 1816
  }) :_state = state {
    _valueIndicatorAnimation = CurvedAnimation(
      parent: _state.valueIndicatorController,
      curve: Curves.fastOutSlowIn,
    );
  }

1817 1818
  late Animation<double> _valueIndicatorAnimation;
  late _RangeSliderState _state;
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840

  @override
  bool get sizedByParent => true;

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

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

  @override
  void paint(PaintingContext context, Offset offset) {
1841 1842
    _state.paintBottomValueIndicator?.call(context, offset);
    _state.paintTopValueIndicator?.call(context, offset);
1843
  }
1844 1845 1846 1847 1848

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