Communitygithub.com

ComeOnOliver/skillshub

在 Flutter 中实现动画的全面指南。适用于为 Flutter 应用添加动效和视觉特效:隐式动画(AnimatedContainer、AnimatedOpacity、TweenAnimationBuilder)、显式动画(AnimationController、Tween、AnimatedWidget/AnimatedBuilder)、Hero 动画(共享元素过渡)、交错动画(顺序/重叠)以及基于物理的动画。包含选择正确动画类型的工作流程、实现模式以及性能和用户体验的最佳实践。

skillshub 是什么?

该技能提供了一套完整的 Flutter 动画实现指南,从基础的隐式动画到复杂的基于物理的动画,帮助开发者选择合适的动画类型并高效实现。它详细介绍了隐式动画(如 AnimatedContainer 和 TweenAnimationBuilder)用于简单属性变化,显式动画(包括 AnimationController、Tween 和 AnimatedBuilder)用于完全控制动画生命周期,Hero 动画用于屏幕间的共享元素过渡,以及交错动画和基于物理的动画(如 SpringSimulation)。技能强调最佳实践,包括正确处理控制器生命周期、使用 AnimatedBuilder 替代 setState 以提高性能,以及通过 Interval 控制动画时序。适用于需要为 Flutter 应用添加动效的开发者,支持所有主流 Flutter 平台(Android、iOS、Web、Desktop)。通过清晰的工作流程和代码示例,该技能确保了动画的流畅性和可维护性。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/madteacher/flutter-animations

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Flutter 动画

概述

在 Flutter 中创建流畅、高性能的动画,为每个用例选择合适的方法。本技能涵盖完整的动画工作流程:从选择隐式/显式方法到实现复杂效果如 Hero 过渡和交错动画。

动画类型决策树

根据需求选择合适的动画类型:

隐式动画 - 适用于以下情况:

  • 对单个属性(颜色、大小、位置)进行动画处理
  • 动画由状态变化触发
  • 无需精细控制

显式动画 - 适用于以下情况:

  • 需要完全控制动画生命周期
  • 同时处理多个属性的动画
  • 需要对动画状态变化做出响应
  • 创建自定义动画或过渡

Hero 动画 - 适用于以下情况:

  • 在两个屏幕之间共享元素
  • 创建共享元素过渡
  • 用户期望元素在路由之间“飞”动

交错动画 - 适用于以下情况:

  • 多个动画应顺序或重叠运行
  • 创建涟漪效果或顺序显示
  • 按顺序动画列表项

基于物理的动画 - 适用于以下情况:

  • 动画应感觉自然/符合物理规律
  • 弹簧行为、滚动手势
  • 可拖拽交互

隐式动画

隐式动画在属性变化时自动处理动画。无需控制器。

常见隐式组件

AnimatedContainer - 对多个属性(大小、颜色、装饰、内边距)进行动画:

AnimatedContainer(
  duration: const Duration(milliseconds: 300),
  curve: Curves.easeInOut,
  width: _expanded ? 200 : 100,
  height: _expanded ? 200 : 100,
  color: _expanded ? Colors.blue : Colors.red,
  child: const FlutterLogo(),
)

AnimatedOpacity - 简单的淡入淡出动画:

AnimatedOpacity(
  opacity: _visible ? 1.0 : 0.0,
  duration: const Duration(milliseconds: 300),
  child: const Text('Hello'),
)

TweenAnimationBuilder - 无需模板代码的自定义补间动画:

TweenAnimationBuilder<double>(
  tween: Tween<double>(begin: 0, end: 1),
  duration: const Duration(seconds: 1),
  builder: (context, value, child) {
    return Opacity(
      opacity: value,
      child: Transform.scale(
        scale: value,
        child: child,
      ),
    );
  },
  child: const FlutterLogo(),
)

其他隐式组件:

  • AnimatedPadding - 内边距动画
  • AnimatedPositioned - 位置动画(在 Stack 中)
  • AnimatedAlign - 对齐动画
  • AnimatedContainer - 多个属性
  • AnimatedSwitcher - 组件之间的交叉淡入淡出
  • AnimatedDefaultTextStyle - 文本样式动画

最佳实践

  • 简单情况下优先使用隐式动画
  • 使用适当的曲线实现自然运动(参见 Curves 类)
  • 设置 curve 和 duration 以获得可预测行为
  • 需要时使用 onEnd 回调
  • 避免嵌套隐式动画以确保性能

显式动画

显式动画通过 AnimationController 提供完全控制。

核心组件

AnimationController - 驱动动画:

late AnimationController _controller;

@override
void initState() {
  super.initState();
  _controller = AnimationController(
    duration: const Duration(seconds: 2),
    vsync: this,
  );
}

@override
void dispose() {
  _controller.dispose();
  super.dispose();
}

Tween - 在起始值和结束值之间插值:

animation = Tween<double>(begin: 0, end: 300).animate(_controller);

CurvedAnimation - 对动画应用曲线:

animation = CurvedAnimation(
  parent: _controller,
  curve: Curves.easeInOut,
);

AnimatedWidget 模式

最适合可复用的动画组件:

class AnimatedLogo extends AnimatedWidget {
  const AnimatedLogo({super.key, required Animation<double> animation})
    : super(listenable: animation);

  @override
  Widget build(BuildContext context) {
    final animation = listenable as Animation<double>;
    return Center(
      child: Container(
        height: animation.value,
        width: animation.value,
        child: const FlutterLogo(),
      ),
    );
  }
}

AnimatedBuilder 模式

最适合带有动画的复杂组件:

class GrowTransition extends StatelessWidget {
  const GrowTransition({
    required this.child,
    required this.animation,
    super.key,
  });

  final Widget child;
  final Animation<double> animation;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: AnimatedBuilder(
        animation: animation,
        builder: (context, child) {
          return SizedBox(
            height: animation.value,
            width: animation.value,
            child: child,
          );
        },
        child: child,
      ),
    );
  }
}

监控动画状态

animation.addStatusListener((status) {
  switch (status) {
    case AnimationStatus.completed:
      _controller.reverse();
      break;
    case AnimationStatus.dismissed:
      _controller.forward();
      break;
    default:
      break;
  }
});

多动画同时运行

class AnimatedLogo extends AnimatedWidget {
  const AnimatedLogo({super.key, required Animation<double> animation})
    : super(listenable: animation);

  static final _opacityTween = Tween<double>(begin: 0.1, end: 1);
  static final _sizeTween = Tween<double>(begin: 0, end: 300);

  @override
  Widget build(BuildContext context) {
    final animation = listenable as Animation<double>;
    return Center(
      child: Opacity(
        opacity: _opacityTween.evaluate(animation),
        child: Container(
          height: _sizeTween.evaluate(animation),
          width: _sizeTween.evaluate(animation),
          child: const FlutterLogo(),
        ),
      ),
    );
  }
}

内置显式过渡

Flutter 提供了可立即使用的过渡:

  • FadeTransition - 淡入淡出动画
  • ScaleTransition - 缩放动画
  • SlideTransition - 滑动动画
  • SizeTransition - 大小动画
  • RotationTransition - 旋转动画
  • PositionedTransition - 位置动画(在 Stack 中)

示例:

FadeTransition(
  opacity: _animation,
  child: const FlutterLogo(),
)

性能提示

  • 组件移除时销毁控制器
  • 使用 AnimatedBuilder 以优化重建
  • 避免在动画监听器中使用 setState()(使用 AnimatedWidget/AnimatedBuilder)
  • 调试时使用 timeDilation 减慢动画速度

Hero 动画

Hero 动画在屏幕之间创建共享元素过渡。

基本 Hero 动画

源屏幕:

Hero(
  tag: 'hero-image',
  child: Image.asset('images/logo.png'),
)

目标屏幕:

Hero(
  tag: 'hero-image',  // 相同的 tag!
  child: Image.asset('images/logo.png'),
)

完整示例

class PhotoHero extends StatelessWidget {
  const PhotoHero({
    super.key,
    required this.photo,
    this.onTap,
    required this.width,
  });

  final String photo;
  final VoidCallback? onTap;
  final double width;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: width,
      child: Hero(
        tag: photo,
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: onTap,
            child: Image.asset(photo, fit: BoxFit.contain),
          ),
        ),
      ),
    );
  }
}

在屏幕之间导航:

Navigator.of(context).push(
  MaterialPageRoute<void>(
    builder: (context) {
      return Scaffold(
        appBar: AppBar(title: const Text('详情')),
        body: Center(
          child: PhotoHero(
            photo: 'images/logo.png',
            width: 300.0,
            onTap: () => Navigator.of(context).pop(),
          ),
        ),
      );
    },
  ),
);

径向 Hero 动画

在过渡期间从圆形变换为矩形:

class RadialExpansion extends StatelessWidget {
  const RadialExpansion({
    super.key,
    required this.maxRadius,
    this.child,
  }) : clipRectSize = 2.0 * (maxRadius / math.sqrt2);

  final double maxRadius;
  final double clipRectSize;
  final Widget? child;

  @override
  Widget build(BuildContext context) {
    return ClipOval(
      child: Center(
        child: SizedBox(
          width: clipRectSize,
          height: clipRectSize,
          child: ClipRect(child: child),
        ),
      ),
    );
  }
}

与 MaterialRectCenterArcTween 一起使用,实现基于中心的插值:

static RectTween _createRectTween(Rect? begin, Rect? end) {
  return MaterialRectCenterArcTween(begin: begin, end: end);
}

Hero 最佳实践

  • 使用唯一且一致的 tag(通常是数据对象本身)
  • 保持路线之间的 hero 组件树相似
  • 将图片包裹在带有透明颜色的 Material 中以获得“弹出”效果
  • 使用 timeDilation 调试过渡
  • 考虑使用 HeroMode 在需要时禁用 hero 动画

交错动画

运行具有不同时机的多个动画。

基本交错动画

所有动画共享一个控制器:

class StaggerAnimation extends StatelessWidget {
  StaggerAnimation({super.key, required this.controller})
    : opacity = Tween<double>(begin: 0.0, end: 1.0).animate(
        CurvedAnimation(
          parent: controller,
          curve: const Interval(0.0, 0.100, curve: Curves.ease),
        ),
      ),
      width = Tween<double>(begin: 50.0, end: 150.0).animate(
        CurvedAnimation(
          parent: controller,
          curve: const Interval(0.125, 0.250, curve: Curves.ease),
        ),
      );

  final AnimationController controller;
  final Animation<double> opacity;
  final Animation<double> width;

  Widget _buildAnimation(BuildContext context, Widget? child) {
    return Container(
      alignment: Alignment.bottomCenter,
      child: Opacity(
        opacity: opacity.value,
        child: Container(
          width: width.value,
          height: 150,
          color: Colors.blue,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: controller,
      builder: _buildAnimation,
    );
  }
}

基于区间的时机

每个动画都有一个介于 0.0 和 1.0 之间的 Interval:

animation = Tween<double>(begin: 0, end: 300).animate(
  CurvedAnimation(
    parent: controller,
    curve: const Interval(
      0.25,  // 在控制器时长的 25% 处开始
      0.50,  // 在控制器时长的 50% 处结束
      curve: Curves.ease,
    ),
  ),
);

常见补间

borderRadius = BorderRadiusTween(
  begin: BorderRadius.circular(4),
  end: BorderRadius.circular(75),
).animate(
  CurvedAnimation(
    parent: controller,
    curve: const Interval(0.375, 0.500, curve: Curves.ease),
  ),
);

交错菜单动画

class _MenuState extends State<Menu> with SingleTickerProviderStateMixin {
  static const _initialDelayTime = Duration(milliseconds: 50);
  static const _itemSlideTime = Duration(milliseconds: 250);
  static const _staggerTime = Duration(milliseconds: 50);
  static const _buttonDelayTime = Duration(milliseconds: 150);
  static const _buttonTime = Duration(milliseconds: 500);

  final _animationDuration =
      _initialDelayTime +
      (_staggerTime * _menuTitles.length) +
      _buttonDelayTime +
      _buttonTime;

  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: _animationDuration,
      vsync: this,
    );
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

交错最佳实践

  • 使用 Interval 在时间上偏移动画
  • 确保控制器时长覆盖所有区间
  • 在区间内使用曲线实现自然运动
  • 考虑使用 timeDilation 调试时机
  • 以增加延迟的方式交错菜单项以产生涟漪效果

基于物理的动画

使用物理模拟创建自然感觉的动画。

弹射动画

_controller.fling(
  velocity: 2.0,  // 每秒单位数
);

自定义物理模拟

_controller.animateWith(
  SpringSimulation(
    spring: const SpringDescription(
      mass: 1,
      stiffness: 100,
      damping: 10,
    ),
    start: 0.0,
    end: 1.0,
    velocity: 0.0,
  ),
);

常见物理模拟

  • SpringSimulation - 弹簧物理
  • BouncingScrollSimulation - 带弹跳的滚动
  • ClampingScrollSimulation - 无弹跳的滚动
  • GravitySimulation - 基于重力的

最佳实践

要做的

  • 在组件销毁时释放 AnimationController
  • 使用 AnimatedBuilder/AnimatedWidget 代替监听器中的 setState()
  • 选择合适的曲线以实现自然运动
  • 使用 timeDilation 调试动画
  • 考虑性能(避免在动画构建中使用重型组件)
  • 在各种设备上测试动画
  • 支持反向动画以获得直观感觉

不要做的

  • 忘记释放 AnimationController(内存泄漏)
  • 在可以使用 AnimatedBuilder 的情况下在动画监听器中使用 setState()
  • 假设动画立即完成(处理 AnimationStatus)
  • 过度动画(动画可能分散用户注意力)
  • 创建感觉“卡顿”的动画(使用平滑曲线)
  • 忽略无障碍功能(尊重 disableAnimations 偏好)

资源

references/

implicit.md - 隐式动画组件的完整参考,包含示例和最佳实践。

explicit.md - 显式动画、AnimationController 和模式的深入探讨。

hero.md - Hero 动画指南,包括标准过渡和径向过渡。

staggered.md - 交错动画模式和时机策略。

physics.md - 基于物理的动画和模拟。

curves.md - Curves 类参考以及如何选择合适的曲线。

...

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相关技能