当我点击 ListTile 后,应该只更改一项,但当我点击时,会更改所有 ListTile。
class _HomeScreenState extends State<HomeScreen> {
bool checked = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: 7,
itemBuilder: (BuildContext context, int i) {
child: return Container(
decoration: new BoxDecoration(
color: checked ? Colors.teal : Colors.white
),
child: ListTile(
onTap: () => setState(() => checked = true),
title: Text("My product"),
),
);
},
),
);
}
}
最佳答案
尝试下面的代码,
class _HomeScreenState extends State<HomeScreen> {
int checkedIndex = -1;
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: 7,
itemBuilder: (BuildContext context, int i) {
return Container(
decoration: BoxDecoration(
color: checkedIndex == i ? Colors.teal : Colors.white
),
child: ListTile(
onTap: () => setState(() => checkedIndex = i),
title: Text("My product"),
),
);
},
),
);
}
}
关于flutter - 仅更改一项项目的样式,而不是更改所有项目的样式。将所有 ListTile 更改为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58798719/