GridView.builder中InkWell点击全部变色问题求助
问题解决:GridView中单个InkWell独立切换选中状态
你当前的问题是因为用了全局的showSelectedTime布尔变量控制所有GridItem的选中状态,点击任意一个item时,所有item都会同步改变颜色。要实现单个item独立切换,需要为每个item维护各自的选中状态。
解决步骤:
- 替换全局布尔值为集合存储选中状态:用
Set<int>保存选中的scheduleId(用ID比index更可靠,避免数据刷新后index变化) - 修改点击逻辑:点击时判断当前item的
scheduleId是否在选中集合中,存在则移除,不存在则添加 - 更新UI判断条件:每个item根据自身
scheduleId是否在集合中来决定颜色样式
修改后的关键代码:
1. 在State类中替换变量:
// 替换原来的bool showSelectedTime = false; Set<int> selectedScheduleIds = {};
2. 修改InkWell的onTap逻辑:
onTap: () { setState(() { int scheduleId = widget.daysGroups?.hours?[index].scheduleId ?? 0; if (selectedScheduleIds.contains(scheduleId)) { selectedScheduleIds.remove(scheduleId); widget.scheduleScreenViewModel?.scheduleIds.remove(scheduleId); } else { selectedScheduleIds.add(scheduleId); widget.scheduleScreenViewModel?.scheduleIds.add(scheduleId); } print(widget.scheduleScreenViewModel?.scheduleIds); }); },
3. 更新UI的颜色判断:
decoration: BoxDecoration( border: Border.all( color: HexColor.fromHex('#f1c452'), ), color: selectedScheduleIds.contains(widget.daysGroups?.hours?[index].scheduleId ?? 0) ? HexColor.fromHex('#f1c452') : HexColor.fromHex('#2b2b33'), borderRadius: BorderRadius.circular(10), ), // 文本颜色同理修改 style: appTheme.typographies.interFontFamily.headline6.copyWith( color: selectedScheduleIds.contains(widget.daysGroups?.hours?[index].scheduleId ?? 0) ? HexColor.fromHex('#212129') : HexColor.fromHex('#f1c452'), fontSize: 14, ),
这样每个item就能独立判断自身选中状态,点击时只会改变当前item的颜色,不会影响其他item。
内容的提问来源于stack exchange,提问作者farhan khan
相关产品推荐
相关产品推荐

