[译] 教你如何用 Flutter 的 GestureDetector 构建自定义滑块
import 'package:flutter/material.dart';
class CustomSliderThumbShape extends SliderThumbShape {
// 绘制滑块
Rect paint(PaintingContext context, Offset center, {Animation<double> activationAnimation, bool isDiscrete, TextPainter labelPainter, double value, double textScaleFactor}) {
final canvas = context.canvas;
final paint = Paint()..color = Colors.blue[400];
final radius = 10.0; // 定义圆形滑块的半径
canvas.drawCircle(center, radius, paint);
return Rect.fromLTWH(center.dx - radius, center.dy - radius, 2 * radius, 2 * radius);
}
}
class CustomSliderTrackShape extends SliderTrackShape {
// 绘制轨道
Rect paint(PaintingContext context, Offset offset, {RenderBox parentBox, SliderThemeData sliderTheme, Animation<double> valueIndicatorAnimation, TextDirection textDirection, double textScaleFactor, double trackHeight, bool isDiscrete}) {
final canvas = context.canvas;
final paint = Paint()..color = Colors.blueGrey[400];
final rect = Rect.fromPoints(
Offset(offset.dx, offset.dy + trackHeight / 2),
Offset(offset.dx + parentBox.size.width, offset.dy + trackHeight / 2),
);
canvas.drawRect(rect, paint);
return rect;
}
}
class CustomSliderThumb extends StatefulWidget {
@override
_CustomSliderThumbState createState() => _CustomSliderThumbState();
}
class _CustomSliderThumbState extends State<CustomSliderThumb> {
double _value = 0.0;
void _updateValue(double value) {
setState(() {
_value = value;
});
}
@override
Widget build(BuildContext context) {
return SliderTheme(
data: SliderTheme.of(context).copyWith(
thumbShape: CustomSliderThumbShape(),
trackShape: CustomSliderTrackShape(),
),
child: Slider(
value: _value,
onChanged: _updateValue,
),
);
}
}
这段代码定义了一个自定义滑块滑块形状CustomSliderThumbShape
和自定义滑块轨道形状CustomSliderTrackShape
,并在CustomSliderThumb
这个StatefulWidget
中使用了SliderTheme
来应用这些自定义形状。滑块形状是一个圆形,轨道形状是一个灰色的矩形。滑块的位置通过Slider
的value
属性控制,并且在用户滑动滑块时,通过onChanged
回调更新这个值。这个例子展示了如何使用SliderTheme
来实现自定义滑块组件的样式。
评论已关闭