Flutter Web点击Chip组件触发UnsupportedError(indexed set)问题求助
问题原因分析
错误Unsupported operation: indexed set的核心原因是代码尝试修改一个不可变列表。在你的代码中,listOfChipIndicesCurrentlySeclected参数传入了const [100]——这是一个不可变的常量列表,而ChipList组件在点击Chip时需要动态修改选中项的索引列表,因此触发了这个错误。
解决步骤
- 声明可变状态变量管理选中索引
在你的父StatefulWidget中,定义一个可变的列表状态变量来存储选中的Chip索引:
List<int> _selectedChipIndices = [100]; // 不要加const,保证列表可修改
- 更新ChipList参数与回调逻辑
将原来的常量列表替换为状态变量,并启用extraOnToggle回调来更新选中状态:
ChipList( style: TextStyle(color: primaryBlue), shouldWrap: true, listOfChipNames: _dogNames, extraOnToggle: (index) { setState(() { if (_selectedChipIndices.contains(index)) { _selectedChipIndices.remove(index); } else { _selectedChipIndices.add(index); } }); }, borderRadiiList: const [5], activeBgColorList: const [Colors.white], inactiveBgColorList: const [Colors.white], activeTextColorList: const [Colors.white], listOfChipIndicesCurrentlySeclected: _selectedChipIndices, // 传入可变状态变量 inactiveBorderColorList: [primaryBlue], activeBorderColorList: [primaryBlue], ),
- 可选:排查其他列表参数
其他使用const声明的列表(如borderRadiiList、activeBgColorList)如果仅用于展示无需修改,可保留const;若组件内部需要修改这些列表,同样要改为可变列表。
关键说明
确保父组件是StatefulWidget,这样setState才能正确触发UI更新。ChipList需要修改选中索引列表来同步状态,而常量列表不支持任何修改操作,这就是错误的直接诱因。
内容的提问来源于stack exchange,提问作者ᴅ ᴇ ʙ ᴊ ᴇᴇ ᴛ
相关产品推荐
相关产品推荐

