Slider 是 一个 Material Design widget,用于从一个范围中选定一个值。
Flutter Slider 介绍
slider 可以从连续的值中选值,也可以从非连续的值中选值。默认是从 min 到 max 的连续值中选择值。如果要在非连续的值中选值,需要给 divisions 设置一个值。比如 min is 0.0,max is 50.0 ,divisions is 5,slider 可以选择的值有 0.0,10.0,20.0,30.0,40.0,and 50.0。
- The "thumb" ,当用户拖动它时会水平滑动。
- The "track","thumb" 滑动的轨道。
- The "value indicator",当用户拖动 thumb 选择值的时候会弹出 indicator 指示选中的值。
- The "active" side 是指在 thumb 到 minmum value 的部分。
- The "inactive" side 是指在 thumb 到 maximum value 的部分。
如果 onChanged 是 null或 min..max 无值可选(比如 min 等于 max),slider 会被禁用。
slider 本身不维护任何状态。当状态变化的时候,调用 onChanged。 多数 widget 可以在这里更新 UI。要知道状态什么时候开始变化,什么时候变化结束,可以监听 onChangedStart,onChangedEnd。
默认情况下, slider 会在水平方向尽量宽,垂直方向居中。如果收到的是 unbouned constrains,slider 会尝试 让 track 144px 宽(两边留有空白),在垂直方向收缩。
slider 要求至少有一个父 widget 是 Material widget。
slider 要求至少有一个父 widget 是 MediaQuery widget。
使用 Slider
const Slider({
super.key,
required this.value,
required this.onChanged,
this.onChangeStart,
this.onChangeEnd,
this.min = 0.0,
this.max = 1.0,
this.divisions,
this.label,
this.activeColor,
this.inactiveColor,
this.thumbColor,
this.mouseCursor,
this.semanticFormatterCallback,
this.focusNode,
this.autofocus = false,
})
根据参数,我们把参数都用上。
Container(
decoration: BoxDecoration(border: Border.all(color: Colors.blue)),
width: double.infinity,
height: 200,
child: Slider(
value: _currentSliderValue,
min: 0,
max: 100,
divisions: 5,
label: _currentSliderValue.toString(),
onChangeEnd: (value) {
print('onEnd: $value');
},
onChangeStart: (value) {
print('onStart: $value');
},
activeColor: Colors.green,
inactiveColor: Colors.greenAccent,
thumbColor: Colors.blueGrey,
onChanged: (double value) {
setState(() {
_currentSliderValue = value;
});
},
));
把 100 分成了 5 等分,每次拖动可以变化 20。 我们看到 slider 在水平方向尽量宽,在垂直方向居中。样式方面除了可以直接在 widget 中指定,也可以用SliderThemeData