flutter如何实现进度条

在Flutter中如何实现一个自定义样式的进度条?我尝试使用LinearProgressIndicator,但无法修改其高度和颜色。希望能展示具体的代码示例,包括如何设置进度值、动画效果以及圆角等样式调整。

2 回复

Flutter中实现进度条可使用LinearProgressIndicatorCircularProgressIndicator组件。

  • 线性进度条:LinearProgressIndicator(value: 0.5)
  • 圆形进度条:CircularProgressIndicator()
    通过value属性控制进度(0~1),无value则为无限循环动画。

更多关于flutter如何实现进度条的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,可以通过多种方式实现进度条,主要使用内置的LinearProgressIndicator(线性进度条)和CircularProgressIndicator(圆形进度条)。以下是具体实现方法:

1. 线性进度条

使用LinearProgressIndicator组件,适用于水平进度展示。

LinearProgressIndicator(
  value: 0.5, // 进度值(0.0 ~ 1.0),不设置则为不确定进度
  backgroundColor: Colors.grey[300],
  valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
)

2. 圆形进度条

使用CircularProgressIndicator组件,适用于加载状态。

CircularProgressIndicator(
  value: 0.7,
  strokeWidth: 4.0,
  backgroundColor: Colors.grey,
  valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
)

3. 自定义进度条

使用SizedBoxStackContainer组合实现自定义样式:

SizedBox(
  height: 20,
  child: Stack(
    children: [
      Container(
        height: 10,
        decoration: BoxDecoration(
          color: Colors.grey[300],
          borderRadius: BorderRadius.circular(5),
        ),
      ),
      LayoutBuilder(
        builder: (context, constraints) {
          return Container(
            height: 10,
            width: constraints.maxWidth * 0.6, // 60%进度
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.circular(5),
            ),
          );
        },
      ),
    ],
  ),
)

4. 动态进度条

结合StatefulWidget和定时器实现动态进度:

class ProgressExample extends StatefulWidget {
  @override
  _ProgressExampleState createState() => _ProgressExampleState();
}

class _ProgressExampleState extends State<ProgressExample> {
  double _progress = 0.0;

  void _updateProgress() {
    setState(() {
      _progress += 0.1;
      if (_progress > 1.0) _progress = 0.0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        LinearProgressIndicator(value: _progress),
        ElevatedButton(
          onPressed: _updateProgress,
          child: Text('更新进度'),
        ),
      ],
    );
  }
}

主要属性说明:

  • value:进度值(0.0~1.0),为null时显示不确定进度(循环动画)
  • backgroundColor:背景颜色
  • valueColor:进度颜色,需使用Animation<Color>

根据需求选择合适的组件,通过调整参数即可实现不同样式的进度条。

回到顶部