Flutter中能否实现类似谷歌风格的LinearProgressIndicator?
实现谷歌风格LinearProgressIndicator方案
当然可以实现这种带间距和终止指示器的进度条,原生LinearProgressIndicator无法直接满足需求,我们可以通过Stack自定义组件来实现:
完整实现代码
class GoogleStyleProgressIndicator extends StatelessWidget { final double percentage; final double height; final Color progressColor; final Color backgroundColor; final double indicatorRadius; final double gapWidth; const GoogleStyleProgressIndicator({ super.key, required this.percentage, this.height = 8, this.progressColor = Colors.black, this.backgroundColor = Colors.white, this.indicatorRadius = 6, this.gapWidth = 8, }); @override Widget build(BuildContext context) { return Stack( alignment: Alignment.centerLeft, children: [ // 背景条 Container( height: height, decoration: BoxDecoration( color: backgroundColor, borderRadius: const BorderRadius.only( topRight: Radius.circular(4), bottomLeft: Radius.circular(4), ), ), ), // 进度条(留出与指示器的间距) LayoutBuilder( builder: (context, constraints) { final progressWidth = constraints.maxWidth * percentage; // 进度条宽度 = 总进度宽度 - 间距 - 指示器半径(避免重叠) final barWidth = progressWidth - gapWidth - indicatorRadius; return barWidth > 0 ? Container( width: barWidth, height: height, decoration: BoxDecoration( color: progressColor, borderRadius: const BorderRadius.only( topRight: Radius.circular(4), bottomLeft: Radius.circular(4), ), ), ) : const SizedBox.shrink(); }, ), // 终止指示器圆点 LayoutBuilder( builder: (context, constraints) { final indicatorLeft = constraints.maxWidth * percentage - indicatorRadius; return indicatorLeft >= 0 ? Positioned( left: indicatorLeft, child: Container( width: indicatorRadius * 2, height: indicatorRadius * 2, decoration: BoxDecoration( color: progressColor, shape: BoxShape.circle, ), ), ) : const SizedBox.shrink(); }, ), ], ); } }
使用示例
直接在页面中引入自定义组件即可:
GoogleStyleProgressIndicator( percentage: percentage, // 你的进度值(范围0-1) )
参数自定义说明
percentage: 核心进度占比,必须传入0到1之间的数值height: 进度条整体高度,默认8progressColor: 进度条和指示器的颜色,默认黑色backgroundColor: 进度条背景色,默认白色indicatorRadius: 终止圆形指示器的半径,默认6gapWidth: 进度条末端与指示器之间的间距,默认8
这个组件完美还原了你需要的谷歌风格效果:进度条与右侧剩余背景之间有明显间距,同时带有圆形终止指示器。
内容的提问来源于stack exchange,提问作者Matteo Preda
相关产品推荐
相关产品推荐

