You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Flutter LinearProgressIndicator实现平滑进度填充

实现Flutter LinearProgressIndicator的5秒平滑填充

你的问题在于使用Timer.periodic每隔1秒更新一次进度,导致进度呈步进式变化。要实现平滑填充效果,应该利用Flutter的动画系统,通过AnimationController控制进度的连续过渡。

以下是优化后的实现代码:

import 'package:flutter/material.dart';

class MyFile extends StatefulWidget {
  const MyFile({super.key});

  @override
  State<MyFile> createState() => _MyFileState();
}

class _MyFileState extends State<MyFile> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _progressAnimation;

  @override
  void initState() {
    super.initState();
    // 创建动画控制器,设置总时长为5秒
    _controller = AnimationController(
      duration: const Duration(seconds: 5),
      vsync: this,
    );

    // 创建从0到1的线性动画,绑定控制器
    _progressAnimation = Tween<double>(begin: 0, end: 1).animate(_controller);

    // 启动动画,从0过渡到1
    _controller.forward();
  }

  @override
  void dispose() {
    // 销毁控制器,避免内存泄漏
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: AnimatedBuilder(
          animation: _progressAnimation,
          builder: (context, child) {
            return LinearProgressIndicator(
              value: _progressAnimation.value,
            );
          },
        ),
      ),
    );
  }
}

关键说明:

  • 使用SingleTickerProviderStateMixin为动画提供帧回调支持,确保动画流畅运行。
  • AnimationController控制动画的总时长,forward()方法启动从0到1的进度过渡。
  • Tween<double>定义进度的起始值(0)和结束值(1),结合控制器生成连续变化的进度数值。
  • AnimatedBuilder自动监听动画变化并触发UI重建,无需手动调用setState,性能更优。

如果需要在动画完成后执行额外操作,可给控制器添加状态监听:

@override
void initState() {
  super.initState();
  _controller = AnimationController(
    duration: const Duration(seconds: 5),
    vsync: this,
  );
  _progressAnimation = Tween<double>(begin: 0, end: 1).animate(_controller);
  
  // 监听动画完成事件
  _controller.addStatusListener((status) {
    if (status == AnimationStatus.completed) {
      // 此处添加动画完成后的逻辑,比如重置进度、跳转页面等
      print("进度条填充完成");
    }
  });
  
  _controller.forward();
}

内容的提问来源于stack exchange,提问作者dipansh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 06:22:09