Reputation: 1840
How do I draw a slider with a rounded rectangle track in Flutter?
I have tried using SliderTheme, but when I supply a RoundedRectSliderTrackShape() as the track shape, it does not allow me to specify a border radius.
Is the only way to achieve this by using custom paint?
Upvotes: 3
Views: 1353
Reputation: 723
You can use this code.
import 'package:flutter/material.dart';
class RoundedRectangleSeekbarShape extends SliderComponentShape {
//The radius of the thumb
final double thumbRadius;
//the thickness of the border
final double thickness;
//the roundness of the corners
final double roundness;
RoundedRectangleSeekbarShape(
{this.thumbRadius = 6.0, this.thickness = 2, this.roundness = 6.0});
@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,
bool? isDiscrete,
required TextPainter labelPainter,
required RenderBox parentBox,
required SliderThemeData sliderTheme,
double? value,
double? textScaleFactor,
Size? sizeWithOverflow,
TextDirection? textDirection,
Thumb? thumb,
bool? isPressed}) {
final Canvas canvas = context.canvas;
final rect = Rect.fromCircle(center: center, radius: thumbRadius);
final roundedRectangle = RRect.fromRectAndRadius(
Rect.fromPoints(
Offset(rect.left - 1, rect.top),
Offset(rect.right + 1, rect.bottom),
),
Radius.circular(roundness),
);
final fillPaint = Paint()
..color = Colors.white
..style = PaintingStyle.fill;
final borderPaint = Paint()
..color = sliderTheme.thumbColor!
..strokeWidth = thickness
..style = PaintingStyle.stroke;
canvas.drawRRect(roundedRectangle, fillPaint);
canvas.drawRRect(roundedRectangle, borderPaint);
}
}
//**call from SliderTheme widget.
SliderTheme(
data: SliderTheme.of(context).copyWith(
trackHeight: 1,
activeTrackColor: CustomColors.orange,
inactiveTrackColor: Colors.white,
thumbColor: CustomColors.orange,
overlayShape: RoundSliderOverlayShape(
overlayRadius: 1),
trackShape: RectangularSliderTrackShape(),
rangeThumbShape: RoundedRectangleThumbShape(
thumbRadius: 12,
roundness: 6,
thickness: 1,
),
thumbShape: RoundedRectangleSeekbarShape(
thumbRadius: 12,
roundness: 6,
thickness: 1,
),
),
child: Slider(
value: 0,
onChanged: (rangeValue) {
},
min: 0,
max: 100,
divisions: 100,
),
)
Upvotes: 2