如何在flutter中点击切换按钮更改多个列表颜色



当切换按钮打开时,我想更改ListTile的颜色,这正在发生,但我不能对多个ListTile执行此操作,因为我可以对多个ListTile执行切换按钮。

这是我的代码

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);
});
}
}

我正在尝试在_onProductSelected上的tappedIndex上做一些事情,请帮助如何做到这一点。

您已经在"_selectedProducts"变量中打开了切换按钮的列表

所以你只需要更改一点代码

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);
});
}
}

最新更新