Flutter ListView中选中的ListTile无法修改背景色该如何解决?
问题原因
selectedIndex变量定义在_patientList方法内部,每次setState触发组件重绘时,该方法会重新执行,selectedIndex会被重置为初始null值,导致选中比对逻辑永远不成立,颜色不会生效。同时代码中还存在冗余组件嵌套、无用变量的问题。
修复步骤
- 将
selectedIndex从_patientList方法内部移到当前State类的成员变量位置,和patientController、patientId等同级声明,避免重绘时被重置。你当前代码里定义的isSelected、_selected两个变量全程未被使用,可以直接删除。 - 调整组件结构,不需要把
InkWell嵌套在ListTile的title属性中,直接使用ListTile自带的onTap回调即可,逻辑更简洁。 - 可选优化:
ListView.separated本身自带滚动能力,外层不需要再包裹SingleChildScrollView,避免滚动冲突。
修复后核心代码示例
// 把selectedIndex移到类成员变量位置,不要放在_patientList方法里 int? selectedIndex; Widget _patientList(context, snapshot) { return Container( width: MediaQuery.of(context).size.width * 0.3, height: MediaQuery.of(context).size.height * 0.5, alignment: Alignment.center, child: Column( children: <Widget> [ Container( child: Row( children: <Widget>[ Container( width: MediaQuery.of(context).size.width * 0.25, child: TextField( controller: patientController, decoration: InputDecoration( prefixIcon: Icon(Icons.search), fillColor: Colors.grey.withOpacity(.4), filled: true, hintText: '이름' ), onChanged: (text){ setState(() {}); }, ), ), TextButton( child: Text('조회',style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),), onPressed: (){ patientController.clear(); }, ) ] ) ), SizedBox(height: MediaQuery.of(context).size.height * 0.05), SafeArea( child: Scrollbar( child: ListView.separated( itemCount: snapshot.data.data.length, shrinkWrap: true, itemBuilder: (context, position) { return Container( color: selectedIndex == position? Colors.blue : Colors.white, child: ListTile( title: Text( snapshot.data.data[position].name + '(' + snapshot.data.data[position].birth + '/' + snapshot.data.data[position].sex + ')', style: TextStyle(fontSize: 14), ), onTap: (){ setState(() { selectedIndex = position; }); patientId = snapshot.data.data[position].patientId; print(patientId); }, ) ); }, separatorBuilder: (context, index) { return Divider(height: 0, thickness: 2,); }, ) ) ) ] ) ); }
内容的提问来源于stack exchange,提问作者momo
相关产品推荐
相关产品推荐

