我正在使用AnimatedList
动画图像,因为它们从列表中添加和删除。
我一直有两个问题,我认为这两个问题是相关的。
- 删除项目后,它会在动画期间呈现下一个索引。例如,它不是显示自己,索引 0,而是在动画出来时呈现索引 1。
- 删除列表中的最后一个索引,导致
RangeError (index): Invalid value: Only valid value is ...
.
这会让我相信我只是在操作一个不同步的索引,但是重新创建一个非常简单的代码示例,仍然会产生同样的问题。如下图所示:
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])),
),
);
}