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

Flutter:如何传递多组单值ChoiceChip的选中值

解决Flutter多组ChoiceChip选中索引冲突问题

原方案仅适用于单组ChoiceChip,实现多组时共用同一个选中索引变量会导致各组选中状态相互干扰。核心问题是需要为每组ChoiceChip单独维护选中状态,下面是具体解决方法:

解决方案思路

使用Map存储不同组的选中索引,每个组对应一个唯一标识键(key),以此独立管理每组的选中状态,避免相互覆盖。

修改后的完整代码

class _MyHomePageState extends State<MyHomePage> {
  // 用Map存储每组的选中索引,key为组标识,value为选中索引
  Map<String, int> _selectedIndices = {
    'groupA': 0,
    'groupB': 0,
  };

  Widget _buildChips(List<String> options, String groupKey) {
    List<Widget> chips = [];
    for (int i = 0; i < options.length; i++) {
      ChoiceChip choiceChip = ChoiceChip(
        selected: _selectedIndices[groupKey] == i,
        label: Text(options[i], style: const TextStyle(color: Colors.white)),
        elevation: 3,
        pressElevation: 5,
        backgroundColor: Colors.grey[400],
        selectedColor: Colors.lightGreen,
        onSelected: (bool selected) {
          setState(() {
            if (selected) {
              // 更新对应组的选中索引
              _selectedIndices[groupKey] = i;
            }
          });
        },
      );
      chips.add(choiceChip);
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: chips,
    );
  }

  @override
  Widget build(BuildContext context) {
    // 提前获取各组选中的文本值,方便后续使用
    final selectedA = ['Regular', 'Hard Sleeper', 'Soft Sleeper'][_selectedIndices['groupA']!];
    final selectedB = ['Python', 'Flutter'][_selectedIndices['groupB']!];

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text('Select A value'),
            _buildChips(['Regular', 'Hard Sleeper', 'Soft Sleeper'], 'groupA'),
            const Text('Select B value'),
            _buildChips(['Python', 'Flutter'], 'groupB'),
            ElevatedButton(
              child: const Text('Pass selected A and B values to next screen'),
              onPressed: () {
                print('选中的A值:$selectedA');
                print('选中的B值:$selectedB');
                // 这里可以添加跳转到下一页面并传递值的逻辑
              },
            ),
          ],
        ),
      ),
    );
  }
}

关键修改点说明

  1. 替换单一的_selectedIndex为Map<String, int> _selectedIndices,为每个组分配独立的存储键。
  2. _buildChips方法新增groupKey参数,用于区分不同的ChoiceChip组。
  3. 创建ChoiceChip时,通过_selectedIndices[groupKey] == i判断当前Chip是否选中。
  4. 点击Chip更新状态时,只修改对应组的索引值,不影响其他组。
  5. 在按钮点击事件中,可直接通过索引获取每组选中的文本值,方便传递到下一页面。

后续新增更多组时,只需在_selectedIndices中添加新的键值对,并调用_buildChips时传入对应的groupKey即可,扩展性更强。

内容的提问来源于stack exchange,提问作者Dolly Storey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:36:30