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

Flutter中Choice Chips切换状态后价格无法动态更新问题求助

问题分析

你遇到的问题核心是:价格仅在点击Choice Chip时才会更新,切换操作状态(etatLabel从"Succés"变为"Echec"或反之)时,没有触发价格的重新计算逻辑。当前选中的干预项对应的价格不会自动根据新状态调整,必须重新点击Chip才会执行价格更新代码。


解决方案

1. 抽离价格计算逻辑为独立函数

将价格计算逻辑单独封装成方法,让点击Chip、切换状态时都能调用它更新价格,避免代码重复:

void updatePrice() {
  setState(() {
    if (etatLabel == "Succés") {
      // 找到当前选中的Chip,获取预设价格
      final selectedChip = choiceChipsInterventions.firstWhere(
        (chip) => chip.isSelected,
        orElse: () => choiceChipsInterventions[0],
      );
      price = selectedChip.prix;
    } else if (etatLabel == "Echec") {
      price = (intervention == "SAV sans RDV" || intervention == "PP sans RDV") 
          ? 25 
          : 0;
    }
  });
}

2. 切换状态时主动触发价格更新

假设你有切换状态的控件(比如另一组Choice Chip),在切换etatLabel后立即调用updatePrice():

// 示例:切换状态的Choice Chip回调
onSelected: (isSelected) {
  setState(() {
    etatLabel = isSelected ? "Echec" : "Succés";
  });
  // 状态切换后立即更新价格
  updatePrice();
},

3. 简化Choice Chip的选中回调逻辑

修改原有Choice Chip的onSelected回调,移除冗余的嵌套setState,直接调用统一的价格更新函数:

Wrap(
  runSpacing: spacing,
  spacing: spacing,
  children: choiceChipsInterventions
      .map((cc) => ChoiceChip(
            label: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              child: Container(
                alignment: Alignment.center,
                height: 30,
                width: 100,
                child: Text(cc.label),
              ),
            ),
            labelStyle: const TextStyle(
                color: Colors.white, fontWeight: FontWeight.bold),
            onSelected: (isSelected) => setState(() {
              // 更新所有Chip的选中状态
              choiceChipsInterventions = choiceChipsInterventions
                  .map((otherChip) => otherChip.copy(
                        isSelected: otherChip == cc ? isSelected : false,
                        label: otherChip.label,
                        selectedColor: otherChip.selectedColor,
                        textColor: otherChip.textColor,
                        prix: otherChip.prix,
                      ))
                  .toList();

              // 更新当前选中的干预项
              if (isSelected) {
                intervention = cc.label;
              }

              // 调用统一的价格更新函数
              updatePrice();
            }),
            selected: cc.isSelected,
            selectedColor: etatLabel == "Echec"
                ? const Color.fromARGB(255, 212, 9, 5)
                : Colors.green,
            backgroundColor: const Color(0xFF473F97),
          ))
      .toList(),
),

关键修改说明

  • 统一价格计算逻辑后,无论是点击Chip还是切换状态,都能触发价格更新,解决了状态切换后价格不刷新的问题。
  • 移除嵌套的setState调用,简化代码逻辑,避免不必要的状态重建。
  • 切换状态时主动调用updatePrice(),确保状态变更后价格立即同步。

内容的提问来源于stack exchange,提问作者Fedy Belaid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:15:40