I created a list to try an display the issue I am encountering with flutter.
Every time you click on a list item button, the button below it is removed. As you can see from the gif below when you click on the button it creates a second copy of the bottom element.
Paused mid animation it looks like this:
To create the AnimtedList I started with giving it a global key:
final GlobalKey<AnimatedListState> _ListKey = GlobalKey();
Then I create a list of colors like this:
List<Color> listColors = [Colors.orange, Colors.green, Colors.red, Colors.blue, Colors.yellowAccent, Colors.brown,];
Then I have an AnimatedList like this, which has initial size of the listColors length and child of _buildListItem:
AnimatedList(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
key: _ListKey,
initialItemCount: listColors.length,
itemBuilder: (context, index, animation) {
return _buildListItem(index, animation);
},
),
This is the build list item method, a SizeTransition that has a child of the List_Element:
SizeTransition _buildListItem(int index, Animation<double> animation,) {
return SizeTransition(
sizeFactor: animation,
child: List_Element(index),
);
}
This is the List_Element,the rows of the list with a simple button with color set by the index of the list of colors. In the onPressed method I call the removeFromListFunction to remove the row below.
class List_Element extends StatefulWidget {
int listIndex;
List_Element(int listIndex) {
this.listIndex = listIndex;
}
@override
_List_ElementState createState() => _List_ElementState();
}
class _List_ElementState extends State<List_Element> {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(4),
child: Container(
width: double.infinity,
height: 50,
child: RaisedButton(
color: listColors[widget.listIndex],
elevation: 2,
child: Center(child: Text("List item " + widget.listIndex.toString(), style: TextStyle(fontWeight: FontWeight.bold),),),
onPressed: (){
_removeFromList(widget.listIndex);
},
),
),
);
}
}
This is the removeFromList function:
void _removeFromList(int index) {
listColors.remove(int);
_ListKey.currentState.removeItem(index+1,
(BuildContext context, Animation<double> animation) {
return _buildListItem(index, animation);
});
}
I am not sure if it a problem with animated list or more likely my implementation of it.
Thanks for your help
void _removeFromList(int index) {
listColors.remove(int);
_ListKey.currentState.removeItem(index+1,
(BuildContext context, Animation<double> animation) {
//return _buildListItem(index, animation);
return _buildListItem(index + 1, animation);
});
}
If I'm not mistaken, the reason why this is happening is that you are passing the index of the "currently clicked" button when you are rebuilding the "removed" button. Thus its displaying the clicked button again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With