如何在Flutter中根据待处理天数占比显示CircularPercentIndicator?
解决方案
要实现待处理天数与圆形进度条的关联,按以下步骤修改代码即可:
- 定义常量与状态变量:添加最大天数常量,同时维护当前待处理天数的状态(可根据实际业务逻辑动态赋值)
- 动态计算百分比:用当前待处理天数除以最大天数得到进度条的百分比值(转换为double类型,同时限制在0-1范围内避免异常)
- 更新进度条参数:替换硬编码的百分比值,还可以优化中心文本显示更直观的天数信息
修改后的完整代码片段:
class _ApplyLeaveState extends State<ApplyLeave> { // 定义最大待处理天数常量 static const int maxPendingDays = 20; // 当前待处理天数,可根据实际业务逻辑动态更新 int currentPendingDays = 10; @override Widget build(BuildContext context) { double height = MediaQuery.of(context).size.height; double width = MediaQuery.of(context).size.width; // 计算百分比,确保数值在0-1区间内 double progressPercent = (currentPendingDays / maxPendingDays).clamp(0.0, 1.0); return WillPopScope( onWillPop: () async { return false; }, child: Scaffold( backgroundColor: Colors.white, drawer: SideBar(), appBar: AppBar( title: Text(app_leave), ), body: Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(top: 15.0), child: Align( alignment: Alignment.center, child: CircularPercentIndicator( radius: 100.0, lineWidth: 15.0, // 使用计算后的动态百分比 percent: progressPercent, center: Text( // 优化显示,展示当前天数/最大天数 "$currentPendingDays/$maxPendingDays 天", style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.w600, color: Colors.black), ), backgroundColor: Colors.grey, circularStrokeCap: CircularStrokeCap.round, progressColor: Colors.blue, ), ), ), // 原有其他组件... ], ), ), ), ), ); } }
补充说明
- 当
currentPendingDays为10时,progressPercent等于10/20=0.5,进度条会精准显示一半 clamp(0.0,1.0)的作用是:即使待处理天数超过20或为负数,进度条也不会超出正常显示范围- 如果需要动态更新天数,只需调用
setState(() => currentPendingDays = 新数值)就能自动刷新进度条
内容的提问来源于stack exchange,提问作者Sakthivel k
相关产品推荐
相关产品推荐

