[英]How to change multiple listtile color on click on toggle button in flutter
I want to change the color of ListTile when toggle button is on, this is happening, but I can't do this for multiple ListTiles wherease i can on the toggle button for multiple listTile.我想在切换按钮打开时更改 ListTile 的颜色,这种情况正在发生,但我无法对多个 ListTile 执行此操作,而我可以在多个 listTile 的切换按钮上执行此操作。
Here is my code这是我的代码
late int tappedIndex;
@override
void initState() {
super.initState();
tappedIndex = 0;
}
Expanded(
child: ListView.builder(
itemCount: books.length,
itemBuilder: (context, index) {
final book = books[index];
return Column(
children: [
Container(
decoration: BoxDecoration(
color: tappedIndex == index ? Colors.grey[200] : Colors.white,
),
child: ListTile(
dense: true,
trailing: Switch(
value: _selectedProducts.contains(book.id),
onChanged: (bool? selected) {
if (selected != null) {
setState(() {
tappedIndex = index
_onProductSelected(selected, book.id,tappedIndex);
});
}
},
activeTrackColor: HexColor("#b8c2cc"),
activeColor: HexColor("#7367f0"),
),
title: Text(
book.title,)
],
),
),
),
),
],
);
void _onProductSelected(bool selected, productId,tappedindex) {
if (selected == true) {
setState(() {
_selectedProducts.add(productId);
});
} else {
setState(() {
_selectedProducts.remove(productId);
});
}
}
i'm trying to do something on tappedIndex on _onProductSelected
, please help how to do this.我正在尝试在 _onProductSelected 上的
_onProductSelected
上做一些事情,请帮助如何做到这一点。
You have already list of toggle button is on in '_selectedProducts' variable.您已经在“_selectedProducts”变量中打开了切换按钮列表。
So you just change a little code.所以你只需要改变一点代码。
tappedIndex == index ? Colors.grey[200] : Colors.white
->
_selectedProducts.contains(book.id) ? Colors.grey[200] : Colors.white
late int tappedIndex;
@override
void initState() {
super.initState();
tappedIndex = 0;
}
Expanded(
child: ListView.builder(
itemCount: books.length,
itemBuilder: (context, index) {
final book = books[index];
return Column(
children: [
Container(
decoration: BoxDecoration(
color: _selectedProducts.contains(book.id) ? Colors.grey[200] : Colors.white,
),
child: ListTile(
dense: true,
trailing: Switch(
value: _selectedProducts.contains(book.id),
onChanged: (bool? selected) {
if (selected != null) {
setState(() {
tappedIndex = index
_onProductSelected(selected, book.id,tappedIndex);
});
}
},
activeTrackColor: HexColor("#b8c2cc"),
activeColor: HexColor("#7367f0"),
),
title: Text(
book.title,)
],
),
),
),
),
],
);
void _onProductSelected(bool selected, productId,tappedindex) {
if (selected == true) {
setState(() {
_selectedProducts.add(productId);
});
} else {
setState(() {
_selectedProducts.remove(productId);
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.