很多应用程序围绕动态列表构建详情,在添加,删除,修改。
没有动画的话,可能令人感觉不安和混乱,为什么所有东西都在跳跃呢?发生了什么事儿?
AnimatedList提供一种简单的方法使列表成动画
首先提供ItemBuilder,这是一个函数 将为列表的每个索引调用。
因此你可以构建每个项目,你也通过方法得到animation,当添加项目时,它会自动启动。
AnimatedList(
itemBuilder: (context, index, animation) {
return MyListItem(_myItems[index]);
}
)
你可以使用它使项目成为动画
AnimatedList(
itemBuilder: (context, index, animation) {
return SlideTransition(
position: animation.drive(MyTween()),
child: MyListItem(_myItems[index]),
);
}
)
你的动画可以是任何东西
除非开始时清单是空白的,你也想提供initialItemCount
AnimatedList(
initialItemCount: _myItems.length,
itemBuilder: (context, index, animation) {
return SlideTransition(
position: animation.drive(MyTween()),
child: MyListItem(_myItems[index]),
);
}
)
现在你需要告诉AnimatedList底层数据结构有任何添加或删除的内容。
为此,你要调用AnimatedListState上的方法,这个类有方法insertItem & removeItem
AnimatedListState.insertItem
AnimatedListState.removeItem
如何得到AnimatedListState呢?
有两种方法
当你想从列表代码 从其中一个item的内部发起动画时候,可以使用**AnimatedList.of(context)**从其他任何地方的话
AnimatedList.of(context).insertItem(index);
AnimatedList.of(context).removeItem(
index,
(context, animation) => ...
);
另外一种,你需要使用GlobalKey,将其附加到动画列表widget 现在你可以从任何地方点用insertItem或removeItem
final _myListKey = GlobalKey<AnimatedListState>();
// ...
AnimatedList(
key: _myListKey,
initialItemCount: _myItems.length,
itemBuilder: (context, index, animation) {
return MyListItem(_myItems[index]);
},
);
_myListKey.cuttentState.insertItem(index);
AnimatedList.of(context).removeItem(
index,
(context, animation) => ...
);
我们来看看这些方法
使用insertItem,你可以告诉AnimatedList在索引处有一个新item
因此应该开始动画。
要构建新添加的itemAnimated使用ItemBuilder,这已经自定义了
重要的是你不仅要调用AnimatedListState方法
_myListKey.currentState.insertItem(index);
// ...
AnimatedList(
initialItemCount: _myItems.length,
itemBuilder: (context, index, animation) {
return MyListItem(_myItems[index]);
},
);
也要实际地更新你的基础数据
_myItems.insert(index, element);
removeItem也要这样做,你告诉AnimatedList索引项目已被删除,你还需要提供构建器
当widget正在制作动画时以作显示
_myListKey.currentState.removeItem(
index,
(context, animation) =>
MyListItem(removeItem),
);
再说一次,你可以使用的动画已经被提供了,这个动画看起来没有限制任何可能性都存在
要记住,删除底层数据结构的item,这是非常重要的
var removedItem = myItems.removeAt(index);
如果想了解有关AnimatedList的内容,或者关于Flutter的其他功能,请访问flutter.dev
原文翻译自视频:视频地址