如何制作如图所示的自定义进度条组件?percent_indicator包无法满足需求
实现自定义分段进度条的方案
你可以通过手动自定义Widget来实现这种带刻度和数值的分段进度条,目前没有完全匹配该样式的现成包,以下是具体实现思路和代码示例(基于Flutter环境):
核心实现思路
用Stack和Row组合以下元素:
- 灰色背景进度条
- 彩色进度填充条
- 垂直刻度线+百分比数值标记
- 可选的当前进度提示文本
完整代码示例
import 'package:flutter/material.dart'; class SegmentedProgressBar extends StatelessWidget { final double progress; // 范围0-1,比如0.6代表60% final int segments; // 分段数量,对应刻度数 final Color backgroundColor; final Color progressColor; final TextStyle labelStyle; const SegmentedProgressBar({ super.key, required this.progress, this.segments = 5, this.backgroundColor = const Color(0xFFE0E0E0), this.progressColor = const Color(0xFF4CAF50), this.labelStyle = const TextStyle(fontSize: 12, color: Colors.black87), }); @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ // 进度条主体 Stack( alignment: Alignment.centerLeft, children: [ // 背景条 Container( height: 8, width: double.infinity, decoration: BoxDecoration( color: backgroundColor, borderRadius: BorderRadius.circular(4), ), ), // 进度填充条 Container( height: 8, width: double.infinity * progress, decoration: BoxDecoration( color: progressColor, borderRadius: BorderRadius.circular(4), ), ), // 刻度与数值标记 Positioned.fill( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: List.generate(segments + 1, (index) { final percentage = (index / segments * 100).round(); return Column( children: [ // 垂直刻度线 Container( width: 2, height: 12, color: Colors.black54, ), // 百分比文本 SizedBox(height: 4), Text('$percentage%', style: labelStyle), ], ); }), ), ), ], ), // 当前进度提示(可选) Padding( padding: const EdgeInsets.only(top: 8), child: Text( '当前进度:${(progress * 100).round()}%', style: labelStyle.copyWith(fontWeight: FontWeight.w500), ), ), ], ); } } // 使用示例 class DemoPage extends StatelessWidget { const DemoPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 40), child: SegmentedProgressBar( progress: 0.7, // 70%进度 segments: 5, ), ), ); } }
可定制调整点
- 修改
segments参数可以改变分段数量,匹配图中的刻度数 - 调整
backgroundColor和progressColor自定义颜色 - 修改
labelStyle可以调整数值文本的大小、颜色 - 调整刻度线的高度、宽度和颜色,匹配图中样式
内容的提问来源于stack exchange,提问作者Farid Ahmadov
相关产品推荐
相关产品推荐

