diff --git a/packages/material_ui/lib/src/range_slider.dart b/packages/material_ui/lib/src/range_slider.dart index b2f156c55a7d..5d4149824877 100644 --- a/packages/material_ui/lib/src/range_slider.dart +++ b/packages/material_ui/lib/src/range_slider.dart @@ -1551,8 +1551,21 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix } double _getValueFromGlobalPosition(Offset globalPosition) { - final double visualPosition = - (globalToLocal(globalPosition).dx - _trackRect.left) / _trackRect.width; + final double localDx = globalToLocal(globalPosition).dx; + final double visualPosition; + // Mirror the padded coordinate system used when painting tick marks and + // thumbs on discrete rounded tracks (see _RenderSlider._getValueFromGlobalPosition). + if (isDiscrete && _sliderTheme.rangeTrackShape!.isRounded) { + final double padding = _trackRect.height; + final double adjustedWidth = _trackRect.width - padding; + if (adjustedWidth <= 0.0) { + visualPosition = 0.5; + } else { + visualPosition = (localDx - _trackRect.left - padding / 2) / adjustedWidth; + } + } else { + visualPosition = (localDx - _trackRect.left) / _trackRect.width; + } return _getValueFromVisualPosition(visualPosition); } diff --git a/packages/material_ui/lib/src/slider.dart b/packages/material_ui/lib/src/slider.dart index 87e84ff8c6a1..0b75ab28e702 100644 --- a/packages/material_ui/lib/src/slider.dart +++ b/packages/material_ui/lib/src/slider.dart @@ -1303,6 +1303,13 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { isDiscrete: false, ); + // Tick marks and the thumb are painted in an adjusted coordinate space that + // reserves half a track height of padding on each end for discrete rounded + // tracks, so gesture math needs to account for that same padding to stay + // aligned with the visual tick positions. + double get _discreteRoundedTrackPadding => + (isDiscrete && _sliderTheme.trackShape!.isRounded) ? _trackRect.height : 0.0; + bool get isInteractive => onChanged != null; bool get isDiscrete => divisions != null && divisions! > 0; @@ -1620,8 +1627,16 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { } double _getValueFromGlobalPosition(Offset globalPosition) { - final double visualPosition = - (globalToLocal(globalPosition).dx - _trackRect.left) / _trackRect.width; + final double localDx = globalToLocal(globalPosition).dx; + final double padding = _discreteRoundedTrackPadding; + final double adjustedWidth = _trackRect.width - padding; + // Invert the padded track-geometry formula (see _discreteRoundedTrackPadding) + // so tap coordinates align with the visual tick positions. Without this, the + // snap midpoints in tap space diverge from the visual midpoints between tick + // marks, biasing lower-half taps toward the wrong (lower) division. + final double visualPosition = adjustedWidth <= 0.0 + ? 0.5 + : (localDx - _trackRect.left - padding / 2) / adjustedWidth; return _getValueFromVisualPosition(visualPosition); } @@ -1704,7 +1719,13 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { case SliderInteraction.slideOnly: case SliderInteraction.slideThumb: if (_active && isInteractive) { - final double valueDelta = details.primaryDelta! / _trackRect.width; + // Use the same coordinate width as _getValueFromGlobalPosition so + // that dragging immediately after a tap does not jump. + final double effectiveWidth = _trackRect.width - _discreteRoundedTrackPadding; + if (effectiveWidth <= 0.0) { + break; + } + final double valueDelta = details.primaryDelta! / effectiveWidth; _currentDragValue += switch (textDirection) { TextDirection.rtl => -valueDelta, TextDirection.ltr => valueDelta, diff --git a/packages/material_ui/pending_changelogs/change_2026_09_18_discrete_slider_tap_wrong_value.yaml b/packages/material_ui/pending_changelogs/change_2026_09_18_discrete_slider_tap_wrong_value.yaml new file mode 100644 index 000000000000..0631affaf68b --- /dev/null +++ b/packages/material_ui/pending_changelogs/change_2026_09_18_discrete_slider_tap_wrong_value.yaml @@ -0,0 +1,3 @@ +changelog: | + - Fixes discrete `Slider` and `RangeSlider` with a rounded track selecting the neighboring division when tapping ticks near the ends of the track. +version: patch diff --git a/packages/material_ui/test/range_slider_test.dart b/packages/material_ui/test/range_slider_test.dart index d5d90bb364a2..96e24c315671 100644 --- a/packages/material_ui/test/range_slider_test.dart +++ b/packages/material_ui/test/range_slider_test.dart @@ -4615,6 +4615,91 @@ void main() { await gesture.up(); }); + + // Regression test for https://github.com/flutter/flutter/issues/184391. + // + // Tick marks on a discrete rounded track are painted with half a track height of + // padding at each end, so the snap boundary between two ticks has to sit at their + // visual midpoint. Tapping on the exact tick center can't tell the difference, so + // tap just on either side of the midpoint. + testWidgets('Discrete RangeSlider snaps at the visual midpoint between ticks', ( + WidgetTester tester, + ) async { + const divisions = 10; + var values = const RangeValues(0, 10); + final tickCenters = []; + + await tester.pumpWidget( + MaterialApp( + home: Material( + child: SliderTheme( + data: SliderThemeData( + rangeTickMarkShape: _PositionRecordingRangeTickMarkShape(tickCenters), + ), + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return Center( + child: RangeSlider( + values: values, + max: 10, + divisions: divisions, + onChanged: (RangeValues newValues) => setState(() => values = newValues), + ), + ); + }, + ), + ), + ), + ), + ); + // Later repaints append to the list, so keep only the first frame's ticks. + final List ticks = tickCenters.take(divisions + 1).toList(); + expect(ticks, hasLength(divisions + 1)); + + // A small offset keeps the taps well clear of the exact midpoint while + // staying smaller than the smallest drift of the old formula. + const midpointOffset = 0.05; + double midpointDx(int i) => (ticks[i].dx + ticks[i + 1].dx) / 2; + + // Taps in the lower half move the start thumb. + for (var i = 0; i < 4; i++) { + await tester.tapAt(Offset(midpointDx(i) - midpointOffset, ticks[i].dy)); + await tester.pump(); + expect( + values.start, + i.toDouble(), + reason: 'Just left of the midpoint of ticks $i and ${i + 1}', + ); + + await tester.tapAt(Offset(midpointDx(i) + midpointOffset, ticks[i].dy)); + await tester.pump(); + expect( + values.start, + (i + 1).toDouble(), + reason: 'Just right of the midpoint of ticks $i and ${i + 1}', + ); + } + + // Taps closer to the end thumb than the start thumb (which is now at 4) move + // the end thumb. + for (int i = divisions - 3; i < divisions; i++) { + await tester.tapAt(Offset(midpointDx(i) - midpointOffset, ticks[i].dy)); + await tester.pump(); + expect( + values.end, + i.toDouble(), + reason: 'Just left of the midpoint of ticks $i and ${i + 1}', + ); + + await tester.tapAt(Offset(midpointDx(i) + midpointOffset, ticks[i].dy)); + await tester.pump(); + expect( + values.end, + (i + 1).toDouble(), + reason: 'Just right of the midpoint of ticks $i and ${i + 1}', + ); + } + }); } // A value indicator shape to log labelPainter text. @@ -4655,3 +4740,31 @@ class LoggingRangeSliderValueIndicatorShape extends RangeSliderValueIndicatorSha logPainter?.add(labelPainter); } } + +/// Records the center of each tick mark as it is painted, so tests can tap +/// relative to the real tick marks without duplicating the track geometry math. +class _PositionRecordingRangeTickMarkShape extends RangeSliderTickMarkShape { + _PositionRecordingRangeTickMarkShape(this.positions); + + final List positions; + + @override + Size getPreferredSize({required SliderThemeData sliderTheme, bool isEnabled = false}) { + return Size.zero; + } + + @override + void paint( + PaintingContext context, + Offset center, { + required RenderBox parentBox, + required SliderThemeData sliderTheme, + required Animation enableAnimation, + required Offset startThumbCenter, + required Offset endThumbCenter, + bool isEnabled = false, + required TextDirection textDirection, + }) { + positions.add(center); + } +} diff --git a/packages/material_ui/test/slider_test.dart b/packages/material_ui/test/slider_test.dart index 30c217b8ffc0..cb29d27d0e20 100644 --- a/packages/material_ui/test/slider_test.dart +++ b/packages/material_ui/test/slider_test.dart @@ -5744,6 +5744,189 @@ void main() { await gesture.up(); }); + + // Regression tests for https://github.com/flutter/flutter/issues/184391. + // + // Tick marks are painted at `trackLeft + padding / 2 + i / d * (trackWidth - padding)`, + // where `padding` is the track height on rounded tracks. Tap detection used to + // invert an unpadded formula instead, so the snap boundary between two ticks + // drifted from their visual midpoint by up to `padding / 2` pixels. Tapping + // exactly on a tick center can't expose that (the drift is far smaller than half + // a division), so these tests tap just on either side of each visual midpoint. + for (final (String name, TextDirection textDirection, bool? year2023) + in <(String, TextDirection, bool?)>[ + ('M3', TextDirection.ltr, null), + ('M3 RTL', TextDirection.rtl, null), + ('M3 with year2023 false (gapped track)', TextDirection.ltr, false), + ('M3 with year2023 false (gapped track) RTL', TextDirection.rtl, false), + ]) { + testWidgets('Discrete Slider snaps at the visual midpoint between ticks ($name)', ( + WidgetTester tester, + ) async { + const divisions = 10; + final value = ValueNotifier(0); + addTearDown(value.dispose); + final List tickCenters = await pumpDiscreteSlider( + tester, + value: value, + divisions: divisions, + textDirection: textDirection, + year2023: year2023, + ); + // Ticks are painted left to right in pixel space regardless of text + // direction, so in RTL the tick at pixel index i has the value divisions - i. + double valueOfTick(int pixelIndex) => switch (textDirection) { + TextDirection.ltr => pixelIndex.toDouble(), + TextDirection.rtl => (divisions - pixelIndex).toDouble(), + }; + + // A small offset keeps the taps well clear of the exact midpoint while + // staying smaller than the smallest drift of the old formula. + const midpointOffset = 0.05; + for (var i = 0; i < divisions; i++) { + final double midpointDx = (tickCenters[i].dx + tickCenters[i + 1].dx) / 2; + final double dy = tickCenters[i].dy; + + await tester.tapAt(Offset(midpointDx - midpointOffset, dy)); + await tester.pump(); + expect( + value.value, + valueOfTick(i), + reason: 'Tapping just left of the midpoint between pixel ticks $i and ${i + 1}', + ); + + await tester.tapAt(Offset(midpointDx + midpointOffset, dy)); + await tester.pump(); + expect( + value.value, + valueOfTick(i + 1), + reason: 'Tapping just right of the midpoint between pixel ticks $i and ${i + 1}', + ); + } + }); + } + + testWidgets('Discrete Slider snaps to a tick when tapping its center', ( + WidgetTester tester, + ) async { + const divisions = 10; + final value = ValueNotifier(0); + addTearDown(value.dispose); + final List tickCenters = await pumpDiscreteSlider( + tester, + value: value, + divisions: divisions, + ); + + for (var i = divisions; i >= 0; i--) { + await tester.tapAt(tickCenters[i]); + await tester.pump(); + expect(value.value, i.toDouble(), reason: 'Tapping the center of tick $i'); + } + }); + + testWidgets('Discrete Slider drag after a tap uses the same track coordinates as the tap', ( + WidgetTester tester, + ) async { + // With many divisions, even a small mismatch between the width used to map + // a position to a value and the width used to scale drag deltas adds up to + // more than half a division over a full-track drag. The gapped track has the + // largest padding, which makes the mismatch most visible. + const divisions = 100; + final value = ValueNotifier(0); + addTearDown(value.dispose); + final List tickCenters = await pumpDiscreteSlider( + tester, + value: value, + divisions: divisions, + year2023: false, + ); + + final TestGesture gesture = await tester.startGesture(tickCenters.first); + // Move past the touch slop first so the drag starts mid-gesture and the + // rest of the movement is scaled by the drag delta normalizer. + await gesture.moveBy(const Offset(kTouchSlop * 2, 0)); + await gesture.moveTo(tickCenters.last); + await tester.pump(); + expect(value.value, divisions.toDouble()); + + await gesture.moveTo(tickCenters.first); + await tester.pump(); + expect(value.value, 0.0); + await gesture.up(); + }); +} + +/// Pumps a [Slider] whose tick mark centers are recorded, and returns the +/// centers of the `divisions + 1` ticks painted on the first frame, ordered +/// left to right. +/// +/// Recording the painted positions lets tests tap relative to the real tick +/// marks without duplicating the track geometry math. +Future> pumpDiscreteSlider( + WidgetTester tester, { + required ValueNotifier value, + required int divisions, + TextDirection textDirection = TextDirection.ltr, + bool? year2023, +}) async { + final tickCenters = []; + await tester.pumpWidget( + MaterialApp( + home: Directionality( + textDirection: textDirection, + child: SliderTheme( + data: SliderThemeData(tickMarkShape: _PositionRecordingTickMarkShape(tickCenters)), + child: Material( + child: Center( + child: ValueListenableBuilder( + valueListenable: value, + builder: (BuildContext context, double current, Widget? child) { + return Slider( + year2023: year2023, + max: divisions.toDouble(), + divisions: divisions, + value: current, + onChanged: (double newValue) => value.value = newValue, + ); + }, + ), + ), + ), + ), + ), + ), + ); + // Later repaints append to the list, so keep only the first frame's ticks. + final List firstFrame = tickCenters.take(divisions + 1).toList(); + expect(firstFrame, hasLength(divisions + 1)); + return firstFrame; +} + +/// Records the center of each tick mark as it is painted. +class _PositionRecordingTickMarkShape extends SliderTickMarkShape { + _PositionRecordingTickMarkShape(this.positions); + + final List positions; + + @override + Size getPreferredSize({required SliderThemeData sliderTheme, required bool isEnabled}) { + return Size.zero; + } + + @override + void paint( + PaintingContext context, + Offset center, { + required RenderBox parentBox, + required SliderThemeData sliderTheme, + required Animation enableAnimation, + required Offset thumbCenter, + required bool isEnabled, + required TextDirection textDirection, + }) { + positions.add(center); + } } // A slider value indicator that's a circle with a fixed size and