Flutter AnimatedListView: 带动画的新增删除实现
要实现带动画的新增删除,可以使用 Flutter 中的 AnimatedList 组件。
首先,需要创建一个 AnimatedList 对象,用于展示列表数据。然后,定义一个 List 对象,用于存储列表数据。在列表中新增或删除数据时,需要先更新 List 对象,然后调用 AnimatedList 的 insertItem 或 removeItem 方法,将新增或删除的项添加到 AnimatedList 中,并指定动画效果。
以下是一个简单的示例代码:
class AnimatedListDemo extends StatefulWidget {
@override
_AnimatedListDemoState createState() => _AnimatedListDemoState();
}
class _AnimatedListDemoState extends State<AnimatedListDemo> {
List<String> items = ['Item 1', 'Item 2', 'Item 3'];
final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
void addItem() {
final int index = items.length;
items.add('Item ${index + 1}');
_listKey.currentState!.insertItem(index);
}
void removeItem(int index) {
final item = items.removeAt(index);
_listKey.currentState!.removeItem(
index,
(context, animation) => ListTile(
title: Text(
item,
style: TextStyle(fontSize: 18),
),
trailing: Icon(Icons.delete),
onTap: () => removeItem(index),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AnimatedList Demo'),
),
body: AnimatedList(
key: _listKey,
initialItemCount: items.length,
itemBuilder: (context, index, animation) {
return SlideTransition(
position: Tween<Offset>(
begin: const Offset(-1, 0),
end: Offset.zero,
).animate(animation),
child: ListTile(
title: Text(
items[index],
style: TextStyle(fontSize: 18),
),
trailing: Icon(Icons.delete),
onTap: () => removeItem(index),
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: addItem,
child: Icon(Icons.add),
),
);
}
}
在这个示例中,我们创建了一个列表,初始包含三个项。当用户点击添加按钮时,我们向列表中新增一项,并使用 AnimatedList 的 insertItem 方法实现动画效果。当用户点击某个项的删除按钮时,我们从列表中删除该项,并使用 AnimatedList 的 removeItem 方法实现动画效果。
在 itemBuilder 中,我们使用 SlideTransition 组件为每个项添加了一个向右滑入的动画效果。你也可以使用其他的动画组件,如 FadeTransition、ScaleTransition 等,根据需求选择合适的效果。
需要注意的是,当使用 AnimatedList 进行新增或删除操作时,要确保在对 List 对象进行修改后,及时调用 AnimatedList 的 insertItem 或 removeItem 方法,以保证 UI 能够及时更新。同时,由于 AnimatedList 实现了 StatefulWidget,因此需要使用 GlobalKey 来引用 AnimatedListState,以便在 State 中调用 AnimatedList 的方法。
原文地址: https://www.cveoy.top/t/topic/lEIJ 著作权归作者所有。请勿转载和采集!