You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何自定义LinearProgressIndicator的value属性取值范围

解决LinearProgressIndicator自定义取值范围的问题

核心思路很简单:LinearProgressIndicator的value属性只接受0.0到1.0之间的比例值,所以我们只需要把用户自定义的进度范围(比如0-100、0-10)转换为这个比例即可。具体实现分三步:

1. 更新数据模型,存储自定义范围

首先修改Dhker类,新增两个字段分别保存用户设置的当前进度值和最大进度值,替代原来的indicatorValue:

class Dhker {
  String title;
  double currentProgress; // 用户实际设置的当前进度
  double maxProgress;     // 用户自定义的进度最大值
  int price;
  String content;

  Dhker({
    required this.title,
    required this.currentProgress,
    required this.maxProgress,
    required this.price,
    required this.content,
  });
}

2. 初始化示例数据(适配新模型)

更新你的getLessons列表,给不同条目设置不同的自定义范围:

List getLessons = [
  Dhker(
    title: "默认0-1范围",
    currentProgress: 0.5,
    maxProgress: 1.0,
    price: 20,
    content:"使用原始0-1比例的进度条"),
  Dhker(
    title: "0-100百分比范围",
    currentProgress: 75.0,
    maxProgress: 100.0,
    price: 25,
    content:"显示75%完成度的进度条"),
  Dhker(
    title: "0-10计数范围",
    currentProgress: 6.5,
    maxProgress: 10.0,
    price: 15,
    content:"已完成6.5/10的进度条"),
];

3. 在UI中转换比例并显示

修改makeListTile里的进度条和文本显示逻辑,把自定义范围的值转换成0-1的比例传给LinearProgressIndicator,同时显示用户能看懂的原始数值:

Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: [
    Flexible(
      flex: 4,
      child: LinearProgressIndicator(
        backgroundColor: const Color.fromRGBO(209, 224, 224, 0.2),
        // 计算比例,用clamp确保不会超出0-1的范围
        value: (lesson.currentProgress / lesson.maxProgress).clamp(0.0, 1.0),
        valueColor: const AlwaysStoppedAnimation(Colors.green),
      ),
    ),
    Flexible(
      child: Text(
        // 显示用户熟悉的原始进度格式
        "${lesson.currentProgress.toStringAsFixed(2)}/${lesson.maxProgress.toStringAsFixed(2)}",
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
    ),
  ],
),

4. 适配新增条目的逻辑

最后修改FloatingActionButton的回调,允许用户在添加新条目时设置自定义的进度范围(这里假设你的AddDhkerPage已经更新为支持输入currentProgress和maxProgress):

floatingActionButton: FloatingActionButton(
  onPressed: () {
    showModalBottomSheet(
      context: context,
      builder: (context) => AddDhkerPage(
        (newDhkerTitle, newCurrent, newMax) {
          setState(() {
            getLessons.add(Dhker(
              title: newDhkerTitle,
              currentProgress: newCurrent ?? 0.0,
              maxProgress: newMax ?? 1.0,
              price: 2,
              content: 'content'));
          });
          Navigator.pop(context);
        },
      ));
  },
  child: const Icon(Icons.add),
  backgroundColor: const Color.fromRGBO(32, 45, 62, 1.0),
);

为什么这样有效?

LinearProgressIndicator的value本质是一个完成比例,不管用户需要什么范围,我们只需要把「当前值/最大值」的结果传给它,就能正确显示进度。用clamp(0.0,1.0)是为了防止用户输入的数值超出设定范围(比如当前值大于最大值),避免进度条出现异常。

内容的提问来源于stack exchange,提问作者Abdullah Bahattab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 02:34:05