You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter AnimatedList删除条目时Dismiss动画不流畅 过渡中内容异常

问题修复方案

问题根因

  1. 你在_removeMemoryAtIndex方法中调用slideIt时,固定传入了索引值0,导致动画组件始终读取列表第0位的元素内容,这是动画过程中内容变成第一条的直接原因。
  2. 动画构建过程中若依赖实时数据源的索引取值,当数据源更新后,原索引对应的元素会变为更新后的条目内容,也会导致动画显示异常。

修复代码

修改_removeMemoryAtIndex方法

提前捕获待删除的元素实例,修正传入slideIt的参数:

_removeMemoryAtIndex(int index, Month currentMonth) {
  // 提前捕获待删除的memory实例,避免后续数据源变更后取值错误
  final removedMemory = currentMonth.memories[index];
  listKey.currentState!.removeItem(
    index,
    (_, animation) => slideIt(
      context,
      currentMonth,
      removedMemory, // 直接传递待删除的实例,不再传索引
      CurvedAnimation(
          parent: animation,
          curve: Curves.easeIn,
          reverseCurve: Curves.easeOut),
    ),
    duration: const Duration(
      milliseconds: 500,
    ),
  );

  Provider.of<MemoryImageProvider>(context, listen: false)
      .removeMemoryAt(index: index);
}

修改slideIt方法参数与逻辑

不再接收索引参数,直接使用传入的已捕获的Memory实例:

Widget slideIt(
  BuildContext context,
  Month currentMonth,
  Memory memory, // 直接接收待删除的memory实例
  animation,
) {
  return SlideTransition(
    position: Tween<Offset>(
      begin: const Offset(-1, 0),
      end: Offset.zero,
    ).animate(
      CurvedAnimation(
        parent: animation,
        curve: Curves.easeIn,
        reverseCurve: Curves.easeOut,
      ),
    ),
    child: Column(
      children: [
        MemoryTile(
          memory: memory,
          monthName: currentMonth.name,
          onTapped: () {
            // 通过实例匹配索引,避免索引实时变动导致的错误
            final targetIndex = currentMonth.memories.indexOf(memory);
            if (targetIndex != -1) {
              _removeMemoryAtIndex(targetIndex, currentMonth);
            }
            print('tap on ${memory.description}');
          },
        ),
        SizedBox(
          height: scaleWidth(20),
        ),
      ],
    ),
  );
}

补充说明

如果列表存在重复的Memory实例,可以给每个Memory添加唯一ID,通过ID匹配索引即可,不需要依赖实时索引取值。

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 18:24:02