Flutter开发中如何将ChoiceChip选中的数据传递到ListTile组件
Flutter 实现ChoiceChip选中数据传递到ListTile的方案
实现逻辑
- 在当前页面的State类中新增一个状态变量,用于存储当前选中的ChoiceChip对应数据,比如选中的分类标签、ID等
- 在ChoiceChip的
onSelected回调中,当用户选中某一个芯片时,同步更新这个状态变量的值 - ListTile组件直接绑定这个状态变量,即可自动响应选中数据的变化,完成数据传递
代码修改示例
首先在State类中定义存储选中值的变量,和你原有goodType变量同级即可:
// 仅需要传递标签就存字符串,需要传递完整对象就定义为GoodTypes?类型 String? _selectedGoodLabel;
然后修改你原有ChoiceChip的onSelected逻辑:
Wrap( runSpacing: spacing, spacing: spacing, children: goodType .map((goodTypeItem) => ChoiceChip( label: Text(goodTypeItem.label), labelStyle: GoogleFonts.ubuntu(color: Colors.white), onSelected: (isSelected) => setState(() { goodType = goodType.map((otherChip) { final newChip = otherChip.copy(isSelected: false); return goodTypeItem == newChip ? newChip.copy( isSelected: isSelected) : newChip; }).toList(); // 新增逻辑:更新选中值 if(isSelected) { _selectedGoodLabel = goodTypeItem.label; } else { // 支持取消选中的话就置空,不需要可以去掉 _selectedGoodLabel = null; } }), selected: goodTypeItem.goodSelected, selectedColor: AppColor.yellow, backgroundColor: AppColor.blackrussain, shape: StadiumBorder( side: BorderSide(color: AppColor.yellow), ), )) .toList(), ),
最后直接在ListTile中绑定状态变量即可:
ListTile( title: const Text("已选商品类型"), subtitle: Text(_selectedGoodLabel ?? "暂未选择类型"), // 其他ListTile属性按需配置 )
补充说明
你当前的ChoiceChip是单选逻辑(选中新芯片时会自动取消其他芯片的选中状态),所以仅需要单个状态变量存储选中值即可。如果后续要改成多选场景,只需要把状态变量改为List类型,选中时往列表中添加/移除对应数据即可。
内容的提问来源于stack exchange,提问作者Saad Rahim
相关产品推荐
相关产品推荐

