[英]Change the color of an element when another element is selected in the ListView Flutter
告訴。 當我 select 列表中的一個項目時,該項目的顏色變為綠色,所以我可以 select 所有項目 - 所有項目都將顏色變為綠色。 But I need that when another element is selected, the previous element returns to its previous state. That is, so that only one element can burn green, and not all. 告訴我如何實施? 我會很感激。
代碼
class _ListPoynts extends State<ListPoynts> {
final List<bool> _selected = [];
@override
void initState() {
for (var i = 0; i < poynts.length; i++) {
_selected.add(false);
}
super.initState();
}
ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: poynts.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => Stack(
alignment: Alignment.topRight,
children: [
Positioned(
child: Container(
width: 176,
alignment: Alignment.bottomCenter,
child: InkWell(
onTap: () {
setState(() {
_selected[index] = !_selected.elementAt(index);
});
},
child: Container(
height: 72,
width: 146,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
color: _selected[index]
? constants.Colors.greenMiddle
: constants.Colors.greyDark.withOpacity(0.7),
),
我不想選擇一個列表,而是一個整數。 selectedIndex 例如。 這樣的事情可能會起作用:
class _ListPoynts extends State<ListPoynts> {
int? _selectedIndex;
@override
void initState() {
//no need to do anything here now
super.initState();
}
ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: poynts.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => Stack(
alignment: Alignment.topRight,
children: [
Positioned(
child: Container(
width: 176,
alignment: Alignment.bottomCenter,
child: InkWell(
onTap: () {
setState(() {
_selectedIndex = index;
});
},
child: Container(
height: 72,
width: 146,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
color: _selectedIndex == index
? constants.Colors.greenMiddle
: constants.Colors.greyDark.withOpacity(0.7),
),
使用一個變量來保存選擇的索引項。 如果沒有選擇索引,則使用null
。
class _ListPoynts extends State<ListPoynts> {
int? _selectedIndex; // <-- HERE
@override
Widget build(BuildContext context) {
return ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: poynts.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => Stack(
alignment: Alignment.topRight,
children: [
Positioned(
child: Container(
width: 176,
alignment: Alignment.bottomCenter,
child: InkWell(
onTap: () {
setState(() {
if (_selectedIndex == index) { // <-- HERE
_selectedIndex = null;
} else {
_selectedIndex = index;
}
});
},
child: Container(
height: 72,
width: 146,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
color: _selectedIndex == index
? constants.Colors.greenMiddle
: constants.Colors.greyDark.withOpacity(0.7),
),
),
),
),
),
],
),
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.