Skip to content

Commit e244038

Browse files
authored
[material_ui] Fix discrete Slider selecting the neighboring tick near the track ends (flutter#12927)
Ports flutter#188012 to `material_ui` now that the Material/Cupertino code freeze has lifted, per the instructions in flutter#188444. Original PR description: --- Fixes flutter#194855 Tick marks and the thumb on discrete rounded tracks are *painted* in a padded coordinate space: ``` dx = trackLeft + i/d * (trackWidth − padding) + padding/2 ``` where `padding = trackHeight` (4 px on M2's `RoundedRectSliderTrackShape`, up to 16 px on M3's `GappedSliderTrackShape`). But tap detection inverted a different, unpadded formula, so the snap midpoints in tap space diverged from the visual midpoints between tick marks. Lower-half ticks consistently landed in the wrong snap bucket. Fix: `_getValueFromGlobalPosition` now uses the padded inverse formula when `isDiscrete && trackShape.isRounded`. The drag-delta normalizer in `_handleDragUpdate` is updated to match so a tap followed immediately by a drag is consistent. Applied to both `Slider` and `RangeSlider`. ## Tests Added regression tests to `slider_test.dart` and `range_slider_test.dart`. They fail without the fix and pass with it: - `Slider` snaps at the visual midpoint between every pair of ticks, tapping 0.05px either side of the midpoint, for the default Material 3 track (LTR and RTL) and the gapped track from `Slider.year2023: false` (LTR and RTL), which has the largest padding. Tapping exactly on a tick center can't expose the bug, because the old and new mappings differ by only a couple of pixels there. - A full-track drag after a tap on a 100-division gapped slider, which covers the drag delta normalizer. - `RangeSlider` snaps at the visual midpoint between ticks for both thumbs. - A tick-center sanity check for `Slider`. All of `slider_test.dart` and `range_slider_test.dart` pass locally. --- Fixes flutter#194855 Closes flutter#188012 (superseded by this PR) ## Pre-Review Checklist [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent 140b51f commit e244038

5 files changed

Lines changed: 338 additions & 5 deletions

File tree

‎packages/material_ui/lib/src/range_slider.dart‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1553,8 +1553,21 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix
15531553
}
15541554

15551555
double _getValueFromGlobalPosition(Offset globalPosition) {
1556-
final double visualPosition =
1557-
(globalToLocal(globalPosition).dx - _trackRect.left) / _trackRect.width;
1556+
final double localDx = globalToLocal(globalPosition).dx;
1557+
final double visualPosition;
1558+
// Mirror the padded coordinate system used when painting tick marks and
1559+
// thumbs on discrete rounded tracks (see _RenderSlider._getValueFromGlobalPosition).
1560+
if (isDiscrete && _sliderTheme.rangeTrackShape!.isRounded) {
1561+
final double padding = _trackRect.height;
1562+
final double adjustedWidth = _trackRect.width - padding;
1563+
if (adjustedWidth <= 0.0) {
1564+
visualPosition = 0.5;
1565+
} else {
1566+
visualPosition = (localDx - _trackRect.left - padding / 2) / adjustedWidth;
1567+
}
1568+
} else {
1569+
visualPosition = (localDx - _trackRect.left) / _trackRect.width;
1570+
}
15581571
return _getValueFromVisualPosition(visualPosition);
15591572
}
15601573

‎packages/material_ui/lib/src/slider.dart‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1305,6 +1305,13 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
13051305
isDiscrete: false,
13061306
);
13071307

1308+
// Tick marks and the thumb are painted in an adjusted coordinate space that
1309+
// reserves half a track height of padding on each end for discrete rounded
1310+
// tracks, so gesture math needs to account for that same padding to stay
1311+
// aligned with the visual tick positions.
1312+
double get _discreteRoundedTrackPadding =>
1313+
(isDiscrete && _sliderTheme.trackShape!.isRounded) ? _trackRect.height : 0.0;
1314+
13081315
bool get isInteractive => onChanged != null;
13091316

13101317
bool get isDiscrete => divisions != null && divisions! > 0;
@@ -1622,8 +1629,16 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
16221629
}
16231630

16241631
double _getValueFromGlobalPosition(Offset globalPosition) {
1625-
final double visualPosition =
1626-
(globalToLocal(globalPosition).dx - _trackRect.left) / _trackRect.width;
1632+
final double localDx = globalToLocal(globalPosition).dx;
1633+
final double padding = _discreteRoundedTrackPadding;
1634+
final double adjustedWidth = _trackRect.width - padding;
1635+
// Invert the padded track-geometry formula (see _discreteRoundedTrackPadding)
1636+
// so tap coordinates align with the visual tick positions. Without this, the
1637+
// snap midpoints in tap space diverge from the visual midpoints between tick
1638+
// marks, biasing lower-half taps toward the wrong (lower) division.
1639+
final double visualPosition = adjustedWidth <= 0.0
1640+
? 0.5
1641+
: (localDx - _trackRect.left - padding / 2) / adjustedWidth;
16271642
return _getValueFromVisualPosition(visualPosition);
16281643
}
16291644

@@ -1706,7 +1721,13 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
17061721
case SliderInteraction.slideOnly:
17071722
case SliderInteraction.slideThumb:
17081723
if (_active && isInteractive) {
1709-
final double valueDelta = details.primaryDelta! / _trackRect.width;
1724+
// Use the same coordinate width as _getValueFromGlobalPosition so
1725+
// that dragging immediately after a tap does not jump.
1726+
final double effectiveWidth = _trackRect.width - _discreteRoundedTrackPadding;
1727+
if (effectiveWidth <= 0.0) {
1728+
break;
1729+
}
1730+
final double valueDelta = details.primaryDelta! / effectiveWidth;
17101731
_currentDragValue += switch (textDirection) {
17111732
TextDirection.rtl => -valueDelta,
17121733
TextDirection.ltr => valueDelta,
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
changelog: |
2+
- Fixes discrete `Slider` and `RangeSlider` with a rounded track selecting the neighboring division when tapping ticks near the ends of the track.
3+
version: patch

‎packages/material_ui/test/range_slider_test.dart‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4615,6 +4615,91 @@ void main() {
46154615

46164616
await gesture.up();
46174617
});
4618+
4619+
// Regression test for https://github.com/flutter/flutter/issues/184391.
4620+
//
4621+
// Tick marks on a discrete rounded track are painted with half a track height of
4622+
// padding at each end, so the snap boundary between two ticks has to sit at their
4623+
// visual midpoint. Tapping on the exact tick center can't tell the difference, so
4624+
// tap just on either side of the midpoint.
4625+
testWidgets('Discrete RangeSlider snaps at the visual midpoint between ticks', (
4626+
WidgetTester tester,
4627+
) async {
4628+
const divisions = 10;
4629+
var values = const RangeValues(0, 10);
4630+
final tickCenters = <Offset>[];
4631+
4632+
await tester.pumpWidget(
4633+
MaterialApp(
4634+
home: Material(
4635+
child: SliderTheme(
4636+
data: SliderThemeData(
4637+
rangeTickMarkShape: _PositionRecordingRangeTickMarkShape(tickCenters),
4638+
),
4639+
child: StatefulBuilder(
4640+
builder: (BuildContext context, StateSetter setState) {
4641+
return Center(
4642+
child: RangeSlider(
4643+
values: values,
4644+
max: 10,
4645+
divisions: divisions,
4646+
onChanged: (RangeValues newValues) => setState(() => values = newValues),
4647+
),
4648+
);
4649+
},
4650+
),
4651+
),
4652+
),
4653+
),
4654+
);
4655+
// Later repaints append to the list, so keep only the first frame's ticks.
4656+
final List<Offset> ticks = tickCenters.take(divisions + 1).toList();
4657+
expect(ticks, hasLength(divisions + 1));
4658+
4659+
// A small offset keeps the taps well clear of the exact midpoint while
4660+
// staying smaller than the smallest drift of the old formula.
4661+
const midpointOffset = 0.05;
4662+
double midpointDx(int i) => (ticks[i].dx + ticks[i + 1].dx) / 2;
4663+
4664+
// Taps in the lower half move the start thumb.
4665+
for (var i = 0; i < 4; i++) {
4666+
await tester.tapAt(Offset(midpointDx(i) - midpointOffset, ticks[i].dy));
4667+
await tester.pump();
4668+
expect(
4669+
values.start,
4670+
i.toDouble(),
4671+
reason: 'Just left of the midpoint of ticks $i and ${i + 1}',
4672+
);
4673+
4674+
await tester.tapAt(Offset(midpointDx(i) + midpointOffset, ticks[i].dy));
4675+
await tester.pump();
4676+
expect(
4677+
values.start,
4678+
(i + 1).toDouble(),
4679+
reason: 'Just right of the midpoint of ticks $i and ${i + 1}',
4680+
);
4681+
}
4682+
4683+
// Taps closer to the end thumb than the start thumb (which is now at 4) move
4684+
// the end thumb.
4685+
for (int i = divisions - 3; i < divisions; i++) {
4686+
await tester.tapAt(Offset(midpointDx(i) - midpointOffset, ticks[i].dy));
4687+
await tester.pump();
4688+
expect(
4689+
values.end,
4690+
i.toDouble(),
4691+
reason: 'Just left of the midpoint of ticks $i and ${i + 1}',
4692+
);
4693+
4694+
await tester.tapAt(Offset(midpointDx(i) + midpointOffset, ticks[i].dy));
4695+
await tester.pump();
4696+
expect(
4697+
values.end,
4698+
(i + 1).toDouble(),
4699+
reason: 'Just right of the midpoint of ticks $i and ${i + 1}',
4700+
);
4701+
}
4702+
});
46184703
}
46194704

46204705
// A value indicator shape to log labelPainter text.
@@ -4655,3 +4740,31 @@ class LoggingRangeSliderValueIndicatorShape extends RangeSliderValueIndicatorSha
46554740
logPainter?.add(labelPainter);
46564741
}
46574742
}
4743+
4744+
/// Records the center of each tick mark as it is painted, so tests can tap
4745+
/// relative to the real tick marks without duplicating the track geometry math.
4746+
class _PositionRecordingRangeTickMarkShape extends RangeSliderTickMarkShape {
4747+
_PositionRecordingRangeTickMarkShape(this.positions);
4748+
4749+
final List<Offset> positions;
4750+
4751+
@override
4752+
Size getPreferredSize({required SliderThemeData sliderTheme, bool isEnabled = false}) {
4753+
return Size.zero;
4754+
}
4755+
4756+
@override
4757+
void paint(
4758+
PaintingContext context,
4759+
Offset center, {
4760+
required RenderBox parentBox,
4761+
required SliderThemeData sliderTheme,
4762+
required Animation<double> enableAnimation,
4763+
required Offset startThumbCenter,
4764+
required Offset endThumbCenter,
4765+
bool isEnabled = false,
4766+
required TextDirection textDirection,
4767+
}) {
4768+
positions.add(center);
4769+
}
4770+
}

‎packages/material_ui/test/slider_test.dart‎

Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5815,6 +5815,189 @@ void main() {
58155815

58165816
await gesture.up();
58175817
});
5818+
5819+
// Regression tests for https://github.com/flutter/flutter/issues/184391.
5820+
//
5821+
// Tick marks are painted at `trackLeft + padding / 2 + i / d * (trackWidth - padding)`,
5822+
// where `padding` is the track height on rounded tracks. Tap detection used to
5823+
// invert an unpadded formula instead, so the snap boundary between two ticks
5824+
// drifted from their visual midpoint by up to `padding / 2` pixels. Tapping
5825+
// exactly on a tick center can't expose that (the drift is far smaller than half
5826+
// a division), so these tests tap just on either side of each visual midpoint.
5827+
for (final (String name, TextDirection textDirection, bool? year2023)
5828+
in <(String, TextDirection, bool?)>[
5829+
('M3', TextDirection.ltr, null),
5830+
('M3 RTL', TextDirection.rtl, null),
5831+
('M3 with year2023 false (gapped track)', TextDirection.ltr, false),
5832+
('M3 with year2023 false (gapped track) RTL', TextDirection.rtl, false),
5833+
]) {
5834+
testWidgets('Discrete Slider snaps at the visual midpoint between ticks ($name)', (
5835+
WidgetTester tester,
5836+
) async {
5837+
const divisions = 10;
5838+
final value = ValueNotifier<double>(0);
5839+
addTearDown(value.dispose);
5840+
final List<Offset> tickCenters = await pumpDiscreteSlider(
5841+
tester,
5842+
value: value,
5843+
divisions: divisions,
5844+
textDirection: textDirection,
5845+
year2023: year2023,
5846+
);
5847+
// Ticks are painted left to right in pixel space regardless of text
5848+
// direction, so in RTL the tick at pixel index i has the value divisions - i.
5849+
double valueOfTick(int pixelIndex) => switch (textDirection) {
5850+
TextDirection.ltr => pixelIndex.toDouble(),
5851+
TextDirection.rtl => (divisions - pixelIndex).toDouble(),
5852+
};
5853+
5854+
// A small offset keeps the taps well clear of the exact midpoint while
5855+
// staying smaller than the smallest drift of the old formula.
5856+
const midpointOffset = 0.05;
5857+
for (var i = 0; i < divisions; i++) {
5858+
final double midpointDx = (tickCenters[i].dx + tickCenters[i + 1].dx) / 2;
5859+
final double dy = tickCenters[i].dy;
5860+
5861+
await tester.tapAt(Offset(midpointDx - midpointOffset, dy));
5862+
await tester.pump();
5863+
expect(
5864+
value.value,
5865+
valueOfTick(i),
5866+
reason: 'Tapping just left of the midpoint between pixel ticks $i and ${i + 1}',
5867+
);
5868+
5869+
await tester.tapAt(Offset(midpointDx + midpointOffset, dy));
5870+
await tester.pump();
5871+
expect(
5872+
value.value,
5873+
valueOfTick(i + 1),
5874+
reason: 'Tapping just right of the midpoint between pixel ticks $i and ${i + 1}',
5875+
);
5876+
}
5877+
});
5878+
}
5879+
5880+
testWidgets('Discrete Slider snaps to a tick when tapping its center', (
5881+
WidgetTester tester,
5882+
) async {
5883+
const divisions = 10;
5884+
final value = ValueNotifier<double>(0);
5885+
addTearDown(value.dispose);
5886+
final List<Offset> tickCenters = await pumpDiscreteSlider(
5887+
tester,
5888+
value: value,
5889+
divisions: divisions,
5890+
);
5891+
5892+
for (var i = divisions; i >= 0; i--) {
5893+
await tester.tapAt(tickCenters[i]);
5894+
await tester.pump();
5895+
expect(value.value, i.toDouble(), reason: 'Tapping the center of tick $i');
5896+
}
5897+
});
5898+
5899+
testWidgets('Discrete Slider drag after a tap uses the same track coordinates as the tap', (
5900+
WidgetTester tester,
5901+
) async {
5902+
// With many divisions, even a small mismatch between the width used to map
5903+
// a position to a value and the width used to scale drag deltas adds up to
5904+
// more than half a division over a full-track drag. The gapped track has the
5905+
// largest padding, which makes the mismatch most visible.
5906+
const divisions = 100;
5907+
final value = ValueNotifier<double>(0);
5908+
addTearDown(value.dispose);
5909+
final List<Offset> tickCenters = await pumpDiscreteSlider(
5910+
tester,
5911+
value: value,
5912+
divisions: divisions,
5913+
year2023: false,
5914+
);
5915+
5916+
final TestGesture gesture = await tester.startGesture(tickCenters.first);
5917+
// Move past the touch slop first so the drag starts mid-gesture and the
5918+
// rest of the movement is scaled by the drag delta normalizer.
5919+
await gesture.moveBy(const Offset(kTouchSlop * 2, 0));
5920+
await gesture.moveTo(tickCenters.last);
5921+
await tester.pump();
5922+
expect(value.value, divisions.toDouble());
5923+
5924+
await gesture.moveTo(tickCenters.first);
5925+
await tester.pump();
5926+
expect(value.value, 0.0);
5927+
await gesture.up();
5928+
});
5929+
}
5930+
5931+
/// Pumps a [Slider] whose tick mark centers are recorded, and returns the
5932+
/// centers of the `divisions + 1` ticks painted on the first frame, ordered
5933+
/// left to right.
5934+
///
5935+
/// Recording the painted positions lets tests tap relative to the real tick
5936+
/// marks without duplicating the track geometry math.
5937+
Future<List<Offset>> pumpDiscreteSlider(
5938+
WidgetTester tester, {
5939+
required ValueNotifier<double> value,
5940+
required int divisions,
5941+
TextDirection textDirection = TextDirection.ltr,
5942+
bool? year2023,
5943+
}) async {
5944+
final tickCenters = <Offset>[];
5945+
await tester.pumpWidget(
5946+
MaterialApp(
5947+
home: Directionality(
5948+
textDirection: textDirection,
5949+
child: SliderTheme(
5950+
data: SliderThemeData(tickMarkShape: _PositionRecordingTickMarkShape(tickCenters)),
5951+
child: Material(
5952+
child: Center(
5953+
child: ValueListenableBuilder<double>(
5954+
valueListenable: value,
5955+
builder: (BuildContext context, double current, Widget? child) {
5956+
return Slider(
5957+
year2023: year2023,
5958+
max: divisions.toDouble(),
5959+
divisions: divisions,
5960+
value: current,
5961+
onChanged: (double newValue) => value.value = newValue,
5962+
);
5963+
},
5964+
),
5965+
),
5966+
),
5967+
),
5968+
),
5969+
),
5970+
);
5971+
// Later repaints append to the list, so keep only the first frame's ticks.
5972+
final List<Offset> firstFrame = tickCenters.take(divisions + 1).toList();
5973+
expect(firstFrame, hasLength(divisions + 1));
5974+
return firstFrame;
5975+
}
5976+
5977+
/// Records the center of each tick mark as it is painted.
5978+
class _PositionRecordingTickMarkShape extends SliderTickMarkShape {
5979+
_PositionRecordingTickMarkShape(this.positions);
5980+
5981+
final List<Offset> positions;
5982+
5983+
@override
5984+
Size getPreferredSize({required SliderThemeData sliderTheme, required bool isEnabled}) {
5985+
return Size.zero;
5986+
}
5987+
5988+
@override
5989+
void paint(
5990+
PaintingContext context,
5991+
Offset center, {
5992+
required RenderBox parentBox,
5993+
required SliderThemeData sliderTheme,
5994+
required Animation<double> enableAnimation,
5995+
required Offset thumbCenter,
5996+
required bool isEnabled,
5997+
required TextDirection textDirection,
5998+
}) {
5999+
positions.add(center);
6000+
}
58186001
}
58196002

58206003
// A slider value indicator that's a circle with a fixed size and

0 commit comments

Comments
 (0)