Flutter中如何将CircularProgressIndicator最大值设为自定义目标值?
解决Flutter CircularProgressIndicator适配自定义目标值的问题
因为CircularProgressIndicator的value属性范围固定是0.0到1.0,没法直接修改最大值,核心思路是把你的实际热量值转换成这个区间的比例,具体做法如下:
正确的比例计算逻辑
你需要用当前热量值 ÷ 目标热量值得到比例,这样当当前值等于目标值时,比例刚好是1.0,指示器完全填满;如果当前值小于目标值,比例会在0-1之间,对应进度的百分比。
修改计算代码
把你的math类(建议遵循Dart命名规范改为首字母大写的Math)改成这样,同时处理除数为0和超过目标值的情况:
class Math { final double currentKcal; final double targetKcal; Math({required this.currentKcal, required this.targetKcal}); double get valuePercentage { if (targetKcal <= 0) return 0.0; // 避免除以0报错 // 如果当前值超过目标值,进度固定为1.0,避免value超出范围 return currentKcal / targetKcal > 1.0 ? 1.0 : currentKcal / targetKcal; } }
更新CircularProgressIndicator的使用
在组件中传入当前热量和目标值,获取正确的比例:
child: CircularProgressIndicator( strokeWidth: 10, value: Math( currentKcal: 3216, // 替换为你的实时热量值 targetKcal: kcalData().Target, // 你的目标热量值 ).valuePercentage, backgroundColor: Color.fromARGB(255, 255, 152, 152), color: Color.fromARGB(255, 233, 54, 54), ),
额外提示
如果需要显示超过目标值的具体数值,可以在指示器旁边添加文本组件,比如:
Row( mainAxisAlignment: MainAxisAlignment.center, children: [ CircularProgressIndicator(/* 你的配置 */), SizedBox(width: 16), Text('${currentKcal}/${targetKcal}大卡'), ], )
内容的提问来源于stack exchange,提问作者Maniak
相关产品推荐
相关产品推荐

