使用不同的GlobalKey将小部件区分开来,使它们得到正确的更新。以下是示例代码。
class MyAnimatedList extends StatefulWidget {
@override
_MyAnimatedListState createState() => _MyAnimatedListState();
}
class _MyAnimatedListState extends State {
List _list = ['A', 'B', 'C'];
final GlobalKey _listKey = GlobalKey();
final List> _itemKeys = [
GlobalKey(),
GlobalKey(),
GlobalKey(),
];
@override
Widget build(BuildContext context) {
return AnimatedList(
key: _listKey,
initialItemCount: _list.length,
itemBuilder: (context, index, animation) {
return MyItem(
key: _itemKeys[index],
text: _list[index],
animation: animation,
);
},
);
}
void addItem(String item) {
final newIndex = _list.length;
_list.add(item);
_listKey.currentState.insertItem(newIndex);
}
void removeItem(int index) {
final removedItem = _list.removeAt(index);
_listKey.currentState.removeItem(
index,
(context, animation) => MyItem(
key: _itemKeys[index],
text: removedItem,
animation: animation,
),
);
}
}
class MyItem extends StatefulWidget {
final String text;
final Animation animation;
MyItem({
Key key,
this.text,
this.animation,
}) : super(key: key);
@override
MyItemState createState() => MyItemState();
}
class MyItemState extends State {
@override
Widget build(BuildContext context) {
return SizeTransition(
sizeFactor: widget.animation,
child: ListTile(
title: Text(widget.text),
),
);
}
}