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

使用AnimatedSwitcher切换Column时出现异常跳动动画问题

解决Flutter AnimatedSwitcher切换时的跳动问题

你的问题根源在于两个子Column的高度不一致:

  • Loading状态的Column包含2个骨架组件,总高度为 20(顶部间距) + (75+20)×2 = 210
  • Success状态的Column仅包含1个容器,总高度为 20(顶部间距) + (75+20) = 115

AnimatedSwitcher切换时,父布局会随着子组件的尺寸突变重新计算布局,这就是跳动现象的直接原因。

解决方案1:让两个子组件高度一致

在Success状态的Column中添加占位组件,填充与Loading状态的高度差:

success: (courses, lastPlayedCourse) {
  return Column(
    key: const Key('success'),
    children: [
      const SizedBox(height: 20),
      Padding(
        padding: const EdgeInsets.only(bottom: 20),
        child: Container(
          height: 75,
          width: double.infinity,
          color: Palette.red,
        ),
      ),
      // 占位组件,匹配Loading状态第二个骨架的高度+padding
      const Padding(
        padding: EdgeInsets.only(bottom: 20),
        child: SizedBox(height: 75),
      ),
    ],
  );
},

解决方案2:固定AnimatedSwitcher的容器高度

通过layoutBuilder强制AnimatedSwitcher的容器高度为两个子组件的最大值,避免尺寸突变:

return AnimatedSwitcher(
  duration: defaultAnimationDurationForWidget * 5,
  layoutBuilder: (currentChild, previousChildren) {
    return SizedBox(
      height: 210, // 设为Loading状态的总高度
      child: Stack(
        children: [
          ...previousChildren,
          if (currentChild != null) currentChild,
        ],
      ),
    );
  },
  child: coursesState.when(
    // 原有的loading和success代码
  ),
);

解决方案3:优化动画曲线减少跳动感

如果不想固定高度,可以通过自定义过渡动画,让尺寸变化更平滑:

return AnimatedSwitcher(
  duration: defaultAnimationDurationForWidget * 5,
  switchInCurve: Curves.easeInOut,
  switchOutCurve: Curves.easeInOut,
  transitionBuilder: (child, animation) {
    return SizeTransition(
      sizeFactor: animation,
      child: FadeTransition(
        opacity: animation,
        child: child,
      ),
    );
  },
  child: coursesState.when(
    // 原有的loading和success代码
  ),
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:45:25