Flutter开发:如何为CircularProgressIndicator添加圆角边框?
实现CircularProgressIndicator的圆角效果

要实现图中所示的圆角进度圆环效果,可通过自定义绘制的方式完成,以下是具体方案:
自定义圆角进度组件
借助CustomPaint实现完全自定义的圆角圆环进度条,核心是给画笔设置strokeCap: StrokeCap.round,让进度条两端呈现圆角:
class RoundedCircularProgressIndicator extends StatelessWidget { final double value; final double strokeWidth; final Color color; final Color backgroundColor; const RoundedCircularProgressIndicator({ super.key, required this.value, this.strokeWidth = 4.0, this.color = Colors.blue, this.backgroundColor = Colors.grey, }); @override Widget build(BuildContext context) { return CustomPaint( painter: _RoundedCircularProgressPainter( value: value, strokeWidth: strokeWidth, color: color, backgroundColor: backgroundColor, ), child: SizedBox.square(dimension: strokeWidth * 10), ); } } class _RoundedCircularProgressPainter extends CustomPainter { final double value; final double strokeWidth; final Color color; final Color backgroundColor; _RoundedCircularProgressPainter({ required this.value, required this.strokeWidth, required this.color, required this.backgroundColor, }); @override void paint(Canvas canvas, Size size) { final center = Offset(size.width / 2, size.height / 2); final radius = (size.width - strokeWidth) / 2; // 绘制背景圆环 final backgroundPaint = Paint() ..color = backgroundColor ..style = PaintingStyle.stroke ..strokeWidth = strokeWidth ..strokeCap = StrokeCap.round; canvas.drawCircle(center, radius, backgroundPaint); // 绘制进度圆环 final progressPaint = Paint() ..color = color ..style = PaintingStyle.stroke ..strokeWidth = strokeWidth ..strokeCap = StrokeCap.round; final arcAngle = 2 * pi * value; canvas.drawArc( Rect.fromCircle(center: center, radius: radius), -pi / 2, arcAngle, false, progressPaint, ); } @override bool shouldRepaint(covariant _RoundedCircularProgressPainter oldDelegate) { return value != oldDelegate.value || strokeWidth != oldDelegate.strokeWidth || color != oldDelegate.color || backgroundColor != oldDelegate.backgroundColor; } }
使用示例
在页面中直接调用自定义组件即可:
RoundedCircularProgressIndicator(value: 0.6)
简化方案(Flutter 3.10+)
若不想自定义完整组件,可利用CircularProgressIndicator新增的customPainter参数,直接传入自定义画笔:
CircularProgressIndicator( value: 0.6, strokeWidth: 4, customPainter: _RoundedCircularProgressPainter( value: 0.6, strokeWidth: 4, color: Colors.blue, backgroundColor: Colors.grey, ), )
内容的提问来源于stack exchange,提问作者Mahendra Raj
相关产品推荐
相关产品推荐

