[英]How do I make an icon invisible in a ListView onPressed in Flutter?
I have a listView that displays a horizontal list of elements.我有一个 listView 显示元素的水平列表。 I have positioned an icon on each box.我在每个盒子上都放置了一个图标。 When the user selects or presses that particular icon (add button), it should make the icon invisible so that the user cannot press it again.当用户选择或按下该特定图标(添加按钮)时,它应该使图标不可见,以便用户无法再次按下它。
The problem I have is that ALL the icons then become invisible, for all elements of that listView.我遇到的问题是,对于该 listView 的所有元素,所有图标都变得不可见。
How can I fix this?我怎样才能解决这个问题?
I figured out that the solution will be related to some key value or keys.. so I added a key to the Visible parent widget, but it has made no difference.我发现解决方案将与一些键值或键相关。所以我向 Visible 父小部件添加了一个键,但它没有任何区别。
Here is the code这是代码
Container(
margin: EdgeInsets.symmetric(vertical: 20, horizontal: 10),
height: MediaQuery.of(context).size.height*0.4,
width: MediaQuery.of(context).size.width,
child:
ListView.builder(
primary: false,
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: mylist.length,
itemBuilder: (context, listItemIndicator)
{
// Card details here
Positioned(bottom: 0, right: 0,
child: Visibility(key: UniqueKey(),
visible: isVisible == true ? true : false,
maintainSize: true,
maintainAnimation: true,
maintainState: true,
child: IconButton(
icon: Icon(Icons.add_box), iconSize: 40,
onPressed: ()
{
isVisible = false; //now all elements disappear, not just the one I pressed.
}
}
),
),
),
The cards display with a + icon them.卡片显示时带有 + 图标。 But as I mentioned, when I press the + icon, ALL the elements have their icons made invisible - not just the one I pressed.但正如我所提到的,当我按下 + 图标时,所有元素的图标都变得不可见 - 不仅仅是我按下的那个。
All icons disappear because isVisible
is same for every item.所有图标都消失了,因为每个项目的isVisible
都是相同的。
You can create map of "visibilities"您可以创建“可见性”的 map
Map<int, bool> visibilities = Map.fromIterable(
mylist,
key: (k) => mylist.indexOf(k),
value: (_) => true,
);
and then接着
Visibility(
visible: visibilities[listItemIndicator],
maintainSize: true,
maintainAnimation: true,
maintainState: true,
child: IconButton(
icon: Icon(Icons.add_box),
iconSize: 40,
onPressed: () {
visibilities[listItemIndicator] = false;
},
),
)
OR you can create stateful widget for that button或者您可以为该按钮创建有状态小部件
class CustomButton extends StatefulWidget {
@override
_CustomButtonState createState() => _CustomButtonState();
}
class _CustomButtonState extends State<CustomButton> {
bool visible = true;
@override
Widget build(BuildContext context) {
return Visibility(
visible: visible,
maintainSize: true,
maintainAnimation: true,
maintainState: true,
child: IconButton(
icon: Icon(Icons.add_box),
iconSize: 40,
onPressed: () {
setState(() {
visible = false;
});
},
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.