要实现带动画的新增删除,可以使用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的方法。

Flutter AnimatedListView 带动画的新增删除 怎么做

原文地址: https://www.cveoy.top/t/topic/sHP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录