Flutter AnimatedList Displaying Wrong Index on Remove

322 views Asked by At

I am using an AnimatedList to animate a images as they are added and removed from the list.

I have been having two issues, which I believe are linked.

  1. Upon removal of an item, it renders the next index during animation. E.g. Instead of displaying itself, index 0, it renders index 1 as it animates out.
  2. Removal of the last index in the list, causes RangeError (index): Invalid value: Only valid value is ....

This would have led me to believe I'm just operating an index out of sync, but recreating a very simple code sample, still produces the same issue. As seen below:

List<String> _data = ['banana', 'apple', 'orange'];

@override
Widget build(BuildContext context) {
    return Container(
          height: widget.imageSize,
          child: AnimatedList(
            key: _listKey,
            scrollDirection: Axis.horizontal,
            initialItemCount: _data.length,
            itemBuilder: (context, index, animation) {
              return SizeTransition(
                key: Key('anim key - ${_data[index]}'),
                sizeFactor: animation,
                axis: Axis.horizontal,
                child: FadeTransition(
                  opacity: animation,
                  child: _buildItemBody(index: index),
                ),
              );
            },
          ),
        );
}

Widget _buildItemBody({@required int index}) {
    return GestureDetector(
      onTap:() {
        _data.removeAt(index);
        AnimatedListRemovedItemBuilder builder = (context, animation) {
            return SizeTransition(
                key: Key('anim key - ${_data[index]}'),
                sizeFactor: animation,
                axis: Axis.horizontal,
              child: FadeTransition(
                opacity: animation,
                child: _buildItemBody(index: index),
              ),
            );
          };
          _listKey.currentState.removeItem(index, builder);
      },
      child: Container(
        key: Key('item key - ${_data[index]}'),
        width: widget.imageSize,
        height: widget.imageSize,
        color: Colors.red,
        child: Center(child: Text(_data[index])),
      ),
    );
}
0

There are 0 answers