Flutter如何为列表项绑定选中索引替代布尔值实现选中容器变色
实现方案
不需要额外维护单独的选中状态变量,直接通过当前项是否存在于已选列表判断选中状态即可,也可以选择用索引列表存储选中项,两种方案逻辑互通。
修改要点
- 删除原代码中全局定义的
bool isSelected = false;变量,该全局变量会导致所有选项共用同一个选中状态,不符合多选项交互逻辑 - 遍历
reportReasons时同时获取当前项的索引,点击事件中直接操作已选列表的增删,内置最多选3项的限制 - 每个选项的背景色、文字色直接通过已选列表是否包含当前项判断选中状态,动态切换样式
完整修改后代码
final List<String> reportReasons = [ 'blah', 'blah blah', 'blah blah blah' ]; // 存储选中的举报原因内容 List<String> chosenReasonsToReport = []; // 布局部分 Container( child: Wrap( children: reportReasons.asMap().entries.map((entry) { int index = entry.key; String reportReason = entry.value; // 实时判断当前项是否被选中 bool isItemSelected = chosenReasonsToReport.contains(reportReason); return GestureDetector( onTap: () { setState(() { if (isItemSelected) { // 已选中则移除 chosenReasonsToReport.remove(reportReason); } else { // 未选中且已选数量小于3则添加 if (chosenReasonsToReport.length < 3) { chosenReasonsToReport.add(reportReason); } } print(chosenReasonsToReport); }); }, child: Container( margin: EdgeInsets.only( right: MediaQuery.of(context).size.width * 0.021, bottom: MediaQuery.of(context).size.height * 0.009, ), decoration: BoxDecoration( color: isItemSelected ? const Color(0xff4aa3f8) : const Color(0xff3a327f), borderRadius: BorderRadius.circular(12), border: Border.all( color: Colors.grey[50]!.withOpacity(0.60) ) ), padding: EdgeInsets.symmetric( horizontal: MediaQuery.of(context).size.width * 0.027, vertical: MediaQuery.of(context).size.height * 0.0045, ), child: Text( reportReason, style: TextStyle( fontSize: 13.5, color: isItemSelected ? const Color(0xff231b6a) : null ), ), ), ); }).toList() ), )
如果你更希望用索引跟踪选中状态,只需要把已选列表修改为存储索引的int类型列表即可:
// 存储选中项的索引 List<int> chosenReasonIndexes = [];
对应判断逻辑改为bool isItemSelected = chosenReasonIndexes.contains(index);,点击事件中改为操作索引的增删即可,其余逻辑完全一致。
内容的提问来源于stack exchange,提问作者VegetaSaiyan
相关产品推荐
相关产品推荐

