Flutter中ChoiceChip单选UI异常:选中颜色显示为多选模式
ChoiceChip单选逻辑正常但选中颜色表现为多选模式的解决方法
我实现了自定义FilterChipCustom组件用于筛选,参考教程做了单选筛选逻辑,功能正常,但UI上多个ChoiceChip会同时显示选中颜色,就像多选模式一样。

问题原因
当前代码只修改了点击目标Chip的选中状态_selected[i] = selected,但未将其他所有Chip的选中状态重置为false,导致之前选中的Chip依然保留选中样式,视觉上呈现多选效果。
解决方案
修改onSelected回调逻辑,在设置当前Chip状态前,先将整个_selected数组重置为false,确保同一时间只有一个Chip处于选中状态:
onSelected: (bool selected) { setState(() { attributesSelected = []; // 重置所有Chip的选中状态为false _selected = List.generate(_selected.length, (index) => false); if (selected) { // 设置当前点击的Chip为选中状态 _selected[i] = true; attributesSelected.add(attributesFoundDistinct[i]); filteredByTag = true; // 执行筛选逻辑 snapList = snapListAll; _filteredDogList = snapList .where((dog) => (dog[attributesFoundDistinct[i]] .toLowerCase() .contains(textControllerValue.toLowerCase()))) .toList(); } else { // 取消选中时清空筛选状态 filteredByTag = false; _filteredDogList = snapListAll; } }); }
可选优化(强制单选,不允许取消选中)
如果需求是必须保持一个选中项、不能取消,可去掉else分支,并在点击已选中的Chip时直接返回:
onSelected: (bool selected) { // 点击已选中的Chip时不做操作 if (_selected[i] == true) return; setState(() { attributesSelected = []; _selected = List.generate(_selected.length, (index) => false); _selected[i] = true; attributesSelected.add(attributesFoundDistinct[i]); filteredByTag = true; snapList = snapListAll; _filteredDogList = snapList .where((dog) => (dog[attributesFoundDistinct[i]] .toLowerCase() .contains(textControllerValue.toLowerCase()))) .toList(); }); }
内容的提问来源于stack exchange,提问作者Lash
相关产品推荐
相关产品推荐

