美文网首页
Flutter自定义Widget结合动画实现进度条

Flutter自定义Widget结合动画实现进度条

作者: itfitness | 来源:发表于2022-11-25 07:42 被阅读0次

目录

实现效果

实现步骤

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("开始"))
        ],
      )
    );
  }
}

相关文章

网友评论

      本文标题:Flutter自定义Widget结合动画实现进度条

      本文链接:https://www.haomeiwen.com/subject/zcjxfdtx.html