Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions packages/material_ui/lib/src/range_slider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Comment on lines +1558 to +1568

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using the null-assert operator (!) on _sliderTheme.rangeTrackShape can lead to a runtime crash if the range track shape is null in the theme. It is safer to use optional chaining (?.) with a fallback value to ensure robustness. Additionally, handling the case where _trackRect.width is <= 0.0 in the else branch prevents potential division-by-zero errors.

    if (isDiscrete && (_sliderTheme.rangeTrackShape?.isRounded ?? false)) {
      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 = _trackRect.width <= 0.0
          ? 0.5
          : (localDx - _trackRect.left) / _trackRect.width;
    }

return _getValueFromVisualPosition(visualPosition);
}

Expand Down
27 changes: 24 additions & 3 deletions packages/material_ui/lib/src/slider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Comment on lines +1310 to +1311

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using the null-assert operator (!) on _sliderTheme.trackShape can lead to a runtime crash if the track shape is null in the theme. It is safer to use optional chaining (?.) with a fallback value to ensure robustness.

  double get _discreteRoundedTrackPadding =>
      (isDiscrete && (_sliderTheme.trackShape?.isRounded ?? false)) ? _trackRect.height : 0.0;


bool get isInteractive => onChanged != null;

bool get isDiscrete => divisions != null && divisions! > 0;
Expand Down Expand Up @@ -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);
}

Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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
113 changes: 113 additions & 0 deletions packages/material_ui/test/range_slider_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <Offset>[];

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<Offset> 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.
Expand Down Expand Up @@ -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<Offset> 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<double> enableAnimation,
required Offset startThumbCenter,
required Offset endThumbCenter,
bool isEnabled = false,
required TextDirection textDirection,
}) {
positions.add(center);
}
}
183 changes: 183 additions & 0 deletions packages/material_ui/test/slider_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<double>(0);
addTearDown(value.dispose);
final List<Offset> 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<double>(0);
addTearDown(value.dispose);
final List<Offset> 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<double>(0);
addTearDown(value.dispose);
final List<Offset> 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<List<Offset>> pumpDiscreteSlider(
WidgetTester tester, {
required ValueNotifier<double> value,
required int divisions,
TextDirection textDirection = TextDirection.ltr,
bool? year2023,
}) async {
final tickCenters = <Offset>[];
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: textDirection,
child: SliderTheme(
data: SliderThemeData(tickMarkShape: _PositionRecordingTickMarkShape(tickCenters)),
child: Material(
child: Center(
child: ValueListenableBuilder<double>(
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<Offset> 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<Offset> 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<double> 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
Expand Down
Loading