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

基于图标实现自定义进度条的开发指引请求

自定义盒子式进度条Widget开发方案

核心思路

针对你需要的「用绿色填充盒子数量标识进度」的需求,核心逻辑是根据进度值计算已填充盒子的数量,通过Row或Wrap组件排列一组盒子,区分已填充和未填充的视觉样式即可。

具体实现步骤

  • 定义关键参数:自定义Widget需包含以下核心参数,确保灵活适配场景:

    • progress:0-1区间的进度值(如0.7代表70%进度)
    • totalBoxes:总盒子数量(如12个,全部填充即100%进度)
    • filledColor:已填充盒子的颜色(比如需求中的绿色)
    • unfilledColor:未填充盒子的颜色(比如浅灰色)
    • boxSize:单个盒子的尺寸
    • spacing:盒子之间的间距
  • 计算填充数量:通过(progress * totalBoxes).floor()得到已填充盒子的数量,剩余即为未填充数量。

  • 构建盒子列表:用List.generate生成两组盒子,分别赋予已填充、未填充样式,合并后用Row或Wrap包裹展示。

  • 细节优化:可给盒子添加圆角、阴影,或加入状态切换动画,提升视觉体验。

示例代码片段

class BoxProgressBar extends StatelessWidget {
  final double progress;
  final int totalBoxes;
  final Color filledColor;
  final Color unfilledColor;
  final double boxSize;
  final double spacing;

  const BoxProgressBar({
    super.key,
    required this.progress,
    this.totalBoxes = 10,
    this.filledColor = Colors.green,
    this.unfilledColor = Colors.grey.shade300,
    this.boxSize = 24,
    this.spacing = 8,
  }) : assert(progress >= 0 && progress <= 1, "进度值需在0-1之间");

  @override
  Widget build(BuildContext context) {
    final filledCount = (progress * totalBoxes).floor();
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(totalBoxes, (index) {
        return Padding(
          padding: EdgeInsets.only(right: index != totalBoxes - 1 ? spacing : 0),
          child: Container(
            width: boxSize,
            height: boxSize,
            decoration: BoxDecoration(
              color: index < filledCount ? filledColor : unfilledColor,
              borderRadius: BorderRadius.circular(4),
            ),
          ),
        );
      }),
    );
  }
}

使用方式

在需要展示进度的位置直接调用:

BoxProgressBar(
  progress: 0.6, // 对应60%进度
  totalBoxes: 8,
  boxSize: 20,
)

扩展方向

  • 支持纵向排列:将Row替换为Column即可
  • 添加过渡动画:用AnimatedContainer实现填充状态切换的平滑动画
  • 自定义盒子形状:修改BorderRadius实现圆形、胶囊形,或用ClipPath实现特殊形状

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:06:08