正常我们放一个Slider
是这样的
Container(
color: Colors.red,
child: Slider(value: 0.5, onChanged: (value){
},activeColor: Colors.orange,
inactiveColor: Colors.orange,
),
)
image.png
可以看到上下左右有边距,而且左边的轨道高度比右边的要高。
源码里可以看到默认的
shape
里多了一个2的高度
image.png
image.png
image.png
所以要去掉的话,可以从
sliderTheme.trackShape
着手,我们可以自定义一个替换掉,参数给出去,如果想要多余的高度也可以加上。
import 'package:flutter/material.dart';
class WDCustomTrackShape extends RoundedRectSliderTrackShape {
WDCustomTrackShape({this.addHeight = 0});
//增加选中滑块的高度,系统默认+2·
double addHeight;
///去掉默认边距
Rect getPreferredRect({
required RenderBox parentBox,
Offset offset = Offset.zero,
required SliderThemeData sliderTheme,
bool isEnabled = false,
bool isDiscrete = false,
}) {
final double trackHeight = sliderTheme.trackHeight??1;
final double trackLeft = offset.dx;
final double trackTop =
offset.dy + (parentBox.size.height - trackHeight) / 2;
final double trackWidth = parentBox.size.width;
return Rect.fromLTWH(trackLeft, trackTop, trackWidth, trackHeight);
}
@override
void paint(
PaintingContext context,
Offset offset, {
required RenderBox parentBox,
required SliderThemeData sliderTheme,
required Animation enableAnimation,
required TextDirection textDirection,
required Offset thumbCenter,
bool isDiscrete = false,
bool isEnabled = false,
double additionalActiveTrackHeight = 0,
}) {
super.paint(context, offset, parentBox: parentBox,
sliderTheme: sliderTheme,
enableAnimation: enableAnimation,
textDirection: textDirection,
thumbCenter: thumbCenter,
additionalActiveTrackHeight: addHeight
);
}
}
再看看效果
Container(
color: Colors.orange,
child: SliderTheme(
data: SliderThemeData(
trackHeight: 1,
inactiveTrackColor: Colors.blue,
activeTrackColor: Colors.blue,
disabledActiveTrackColor: Colors.blue,
disabledInactiveTrackColor: Colors.blue,
thumbColor: Colors.white,
trackShape: WDCustomTrackShape(addHeight: 0),
),
child: Slider(
value: 0.5,
onChanged: (value){},
),
),
)
image.png
ok 确实没多多余的高度了,但是还是上下有边距,简单,加上如下属性:
overlayShape: RoundSliderOverlayShape(overlayRadius: 0),
image.png
SliderThemeData
还有不少属性,可以自己去探索探索。