Flutter:更改 ListView.builder 中所选按钮的背景颜色
Flutter: Change the background color of selected button in ListView.builder
我有一个项目列表和默认颜色。
List<String> items = ['A', 'B', 'C'];
Color _color = Colors.transparent;
根据我的代码,它更改了按钮的所有背景颜色。
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ElevatedButton(
style: ButtonStyle(backgroundColor: MaterialStateProperty.all(_color)),
onPressed: () {
setState(() {
_color = Colors.blue;
});
},
child: Text(items[index]),
);
},
);
所以,我只想让选中的按钮改变背景颜色。
请试试这个
List<String> items = ['A', 'B', 'C'];
List<Color> _color = [Colors.transparent,Colors.transparent,Colors.transparent ];
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(_color[index])),
onPressed: () {
setState(() {
if (_color[index] == Colors.blue) {
_color[index] = Colors.transparent;
} else {
_color[index] = Colors.blue;
}
});
},
child: Text(items[index]),
);
},
);
输出:
我有一个项目列表和默认颜色。
List<String> items = ['A', 'B', 'C'];
Color _color = Colors.transparent;
根据我的代码,它更改了按钮的所有背景颜色。
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ElevatedButton(
style: ButtonStyle(backgroundColor: MaterialStateProperty.all(_color)),
onPressed: () {
setState(() {
_color = Colors.blue;
});
},
child: Text(items[index]),
);
},
);
所以,我只想让选中的按钮改变背景颜色。
请试试这个
List<String> items = ['A', 'B', 'C'];
List<Color> _color = [Colors.transparent,Colors.transparent,Colors.transparent ];
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(_color[index])),
onPressed: () {
setState(() {
if (_color[index] == Colors.blue) {
_color[index] = Colors.transparent;
} else {
_color[index] = Colors.blue;
}
});
},
child: Text(items[index]),
);
},
);
输出: