目录
![](https://img.haomeiwen.com/i8850933/0ea4e306d31455d3.png)
实现效果
![](https://img.haomeiwen.com/i8850933/c3809628aa929fb4.gif)
实现步骤
1.创建自定义Widget
先创建一个自定义的Widget,其实就是一个简单的画线,将线的两端设置为圆的,其中进度为外部创建时传递的值,也就是接下来动画要传递的值
class ProgressPaint extends CustomPainter{
var drawPaint = Paint()
..strokeCap = StrokeCap.round
..style = PaintingStyle.stroke
..color = Colors.blue
..isAntiAlias = true
..strokeWidth = 20;
final double progress;
ProgressPaint({
required this.progress
});
@override
void paint(Canvas canvas, Size size) {
var progressVal = (size.width - 10) * progress / 100;
canvas.drawLine(Offset(10,10), Offset(progressVal,10), drawPaint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
2.实现动画
动画的实现需要AnimationController和Animation然后在Animation的监听回调函数中更新State,代码如下:
class _MainPageState extends State<MainPage> with SingleTickerProviderStateMixin{
late Animation<double> animation;
late AnimationController controller;
@override
void initState() {
// TODO: implement initState
super.initState();
controller = AnimationController(
duration: const Duration(seconds: 5), vsync: this);
//进度条进度从0到1
animation = Tween(begin: 0.0, end: 100.0).animate(controller)..addListener(() {
setState(() => {});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("动画"),
),
body: Column(
children: [
CustomPaint(
size: Size(double.infinity,20),
painter: ProgressPaint(progress: animation.value),
),
ElevatedButton(onPressed: (){
//启动动画
controller.forward();
}, child: Text("开始"))
],
)
);
}
}
网友评论