在 Flutter 中,我們經常使用 CircularProgressIndicator
來展示加載進度。但是你是否注意到:它的進度端始終是“平頭”的(直角)?
這在一些 UI 設計中并不美觀,特別是想實現類似 Apple 健身環那樣“前端圓清澈”效果時,就需要一個帶圓角的圓形進度條。
🛠 方法一:使用 CustomPaint 自繪圓角進度
Flutter 的 Canvas 提供了繪制弧形和給進度端點設置樣式的能力,我們只需設置 Paint.strokeCap = StrokeCap.round
就可以讓進度端頭變成圓角。
→ 實現代碼:
class RoundedCircularProgressIndicator extends StatelessWidget {final double progress;final double size;final double strokeWidth;final Color backgroundColor;final Color progressColor;const RoundedCircularProgressIndicator({super.key,required this.progress,this.size = 40.0,this.strokeWidth = 6.0,this.backgroundColor = const Color(0xFFE0E0E0),this.progressColor = Colors.blue,}); Widget build(BuildContext context) {return SizedBox(width: size,height: size,child: CustomPaint(painter: _RoundedCircularProgressPainter(progress: progress,strokeWidth: strokeWidth,backgroundColor: backgroundColor,progressColor: progressColor,),),);}
}class _RoundedCircularProgressPainter extends CustomPainter {final double progress;final double strokeWidth;final Color backgroundColor;final Color progressColor;_RoundedCircularProgressPainter({required this.progress,required this.strokeWidth,required this.backgroundColor,required this.progressColor,});void paint(Canvas canvas, Size size) {final center = size.center(Offset.zero);final radius = (size.width - strokeWidth) / 2;final rect = Rect.fromCircle(center: center, radius: radius);final backgroundPaint = Paint()..color = backgroundColor..style = PaintingStyle.stroke..strokeWidth = strokeWidth;final progressPaint = Paint()..color = progressColor..style = PaintingStyle.stroke..strokeWidth = strokeWidth..strokeCap = StrokeCap.round; // 圓角關鍵canvas.drawArc(rect, 0, 2 * pi, false, backgroundPaint);canvas.drawArc(rect, -pi / 2, 2 * pi * progress, false, progressPaint);} bool shouldRepaint(CustomPainter oldDelegate) => true;
}
→ 使用示例:
RoundedCircularProgressIndicator(progress: 0.75,size: 80,strokeWidth: 10,backgroundColor: Colors.grey.shade300,progressColor: Colors.green,
),
效果:圓角端頭,進度從頂部開始順時針繪制,大氣現代。
📆 方法二:使用第三方庫 percent_indicator
percent_indicator
是非常流行的進度指示器庫,支持 circularStrokeCap: CircularStrokeCap.round
安裝依賴
dependencies:percent_indicator: ^4.2.5
使用示例
CircularPercentIndicator(radius: 40.0,lineWidth: 8.0,percent: 0.6,circularStrokeCap: CircularStrokeCap.round,backgroundColor: Colors.grey.shade300,progressColor: Colors.purple,
),
很方便,適合快速開發場景。
? Flutter 自帶的 CircularProgressIndicator 存在的限制
Flutter 默認的 CircularProgressIndicator
沒有揭露 strokeCap 設置,不支持圓角端。
如果你想要實現“前端圓角”效果,當前只能選擇:
- 自繪
- 第三方庫
📊 方法對比
方法 | 是否支持圓角 | 自定義能力 | 使用難度 | 推薦度 |
---|---|---|---|---|
CustomPaint 自繪 | ? | 高 | 中 | ???? |
percent_indicator | ? | 中 | 低 | ???? |
CircularProgressIndicator | ? | 低 | 低 | ?? |
? 總結
本文介紹了如何在 Flutter 中實現 帶圓角的圓形進度條,通過:
- 自繪
CustomPaint
- 第三方庫
percent_indicator
這些技巧可以使進度 UI 更加精致,滿足更復雜的產品設計需求。
🐾 后記
如果你正在開發帶上傳進度、音頻處理、視頻模塊等場景,圓角進度條會大大提升用戶體驗。
歡迎點贊、收藏、評論!有任何 Flutter 相關問題也可以留言一起探討!