I'm currently working on a Flutter project and I need assistance with creating a custom shape for the Slider thumb.
I have both a regular Slider and a RangeSlider in my app, and I would like to customize the appearance of the thumb for both of them.
To provide a clear understanding of the issue, I have attached screenshots of both sliders:
You can create a custom thumb shape by extending SliderComponentShape and use this in your Slider:
class AppSliderShape extends SliderComponentShape {
final double thumbRadius;
const AppSliderShape({required this.thumbRadius});
@override
Size getPreferredSize(bool isEnabled, bool isDiscrete) {
return Size.fromRadius(thumbRadius);
}
@override
void paint(
PaintingContext context,
Offset center, {
required Animation<double> activationAnimation,
required Animation<double> enableAnimation,
required bool isDiscrete,
required TextPainter labelPainter,
required RenderBox parentBox,
required SliderThemeData sliderTheme,
required TextDirection textDirection,
required double value,
required double textScaleFactor,
required Size sizeWithOverflow,
}) {
final Canvas canvas = context.canvas;
final paint = Paint()
..style = PaintingStyle.fill
..color = Colors.white;
// draw icon with text painter
const iconData = Icons.drag_handle;
final TextPainter textPainter = TextPainter(textDirection: TextDirection.rtl);
textPainter.text = TextSpan(
text: String.fromCharCode(iconData.codePoint),
style: TextStyle(
fontSize: thumbRadius * 2,
fontFamily: iconData.fontFamily,
color: sliderTheme.thumbColor,
));
textPainter.layout();
final Offset textCenter = Offset(center.dx - (textPainter.width / 2),
center.dy - (textPainter.height / 2));
const cornerRadius = 4.0;
// draw the background shape here..
canvas.drawRRect(
RRect.fromRectXY(
Rect.fromCenter(center: center, width: 30, height: 20), cornerRadius, cornerRadius),
paint,
);
textPainter.paint(canvas, textCenter);
}
}
Then in your SliderTheme:
SliderTheme(
data: SliderThemeData(
thumbColor: Colors.teal,
thumbShape: AppSliderShape(thumbRadius: 10),
),
child: Slider(),
),
You may give a try this
SliderTheme(
data: SliderThemeData(
thumbColor: Colors.green,
thumbShape: RoundSliderThumbShape(enabledThumbRadius: 20)),
child: Slider(
value: _value,
onChanged: (val) {
_value = val;
setState(() {});
},
),
),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With