Communitygithub.com

ComeOnOliver/skillshub

Flutter 動畫的完整實作指南。用於在 Flutter 應用程式中加入動態與視覺效果:隱含動畫(AnimatedContainer、AnimatedOpacity、TweenAnimationBuilder)、明確動畫(AnimationController、Tween、AnimatedWidget/AnimatedBuilder)、Hero 動畫(共享元素轉場)、分階動畫(順序/重疊),以及物理基礎動畫。包含選用合適動畫類型的工作流程、實作模式,以及效能與使用者體驗的最佳做法。

skillshub 是什麼?

此技能提供 Flutter 中各式動畫的完整指南,從隱含動畫(例如 AnimatedContainer 與 AnimatedOpacity)到明確動畫(使用 AnimationController 和 Tween),以及進階技術如 Hero 動畫(共享元素轉場)、分階動畫(利用 Interval 控制時序)和物理基礎動畫(SpringSimulation 等)。它特別適合需要在 Flutter 應用程式中實現流暢、自然動畫效果的開發者。技能中包含了「動畫類型決策樹」,幫助你根據需求選擇最合適的動畫方式,並提供豐富的程式碼範例與最佳實務建議,例如記得銷毀 AnimationController 以避免記憶體洩漏,以及優先使用 AnimatedBuilder 而非在監聽器內呼叫 setState,以提升效能。無論是簡單的單一屬性變化還是複雜的轉場效果,此技能都能有效支援。

相容平台~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 動畫 - 在以下情況使用:

  • 在兩個畫面之間共享元素
  • 建立共享元素轉場
  • 使用者期望元素在路由之間「飛翔」

分階動畫 - 在以下情況使用:

  • 多個動畫應依序或重疊執行
  • 產生漣漪效果或依序揭露
  • 依序動畫化列表項目

物理基礎動畫 - 在以下情況使用:

  • 動畫應感覺自然/符合物理
  • 彈簧行為、捲動手勢
  • 可拖曳互動

隱含動畫

隱含動畫會在屬性變更時自動處理動畫。不需要控制器。

常見的隱含 Widget

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(),
)

其他隱含 widget:

  • AnimatedPadding - 內距動畫
  • AnimatedPositioned - 位置動畫(在 Stack 中)
  • AnimatedAlign - 對齊動畫
  • AnimatedContainer - 多個屬性
  • AnimatedSwitcher - Widget 之間的交叉淡入
  • 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 模式

最適合可重複使用的動畫化 widget:

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 模式

最適合複雜的帶動畫 widget:

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(),
)

效能技巧

  • 在 widget 移除時銷毀控制器
  • 使用 AnimatedBuilder 以獲得最佳重建
  • 避免在動畫監聽器中使用 setState()(使用 AnimatedWidget/AnimatedBuilder)
  • 使用 timeDilation 在除錯時放慢動畫

Hero 動畫

Hero 動畫在畫面之間建立共享元素轉場。

基本 Hero 動畫

來源畫面:

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

目標畫面:

Hero(
  tag: 'hero-image',  // 同一個標籤!
  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('Detail')),
        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 最佳做法

  • 使用獨特且一致的標籤(通常是資料物件本身)
  • 保持路由間的 hero widget 樹相似
  • 將圖片包裝在透明顏色的 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 之間有一個區間:

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 - 基於重力

最佳做法

務必

  • 在 widget 銷毀時處置 AnimationController
  • 使用 AnimatedBuilder/AnimatedWidget 取代在監聽器中使用 setState()
  • 選擇適當的曲線以獲得自然的動態
  • 使用 timeDilation 除錯動畫
  • 考量效能(避免在動畫建構中使用過重的 widget)
  • 在各種裝置上測試動畫
  • 支援反向動畫以獲得直覺感受

避免

  • 忘記處置 AnimationController(記憶體洩漏)
  • 在動畫監聽器中使用 setState(),當 AnimatedBuilder 已足夠時
  • 假設動畫會立即完成(處理 AnimationStatus)
  • 過度動畫化(動畫可能會分散使用者注意力)
  • 建立感覺「不流暢」的動畫(使用平滑曲線)
  • 忽略無障礙功能(尊重 disableAnimations 偏好設定)

資源

references/

implicit.md - 隱含動畫 widget 的完整參考,包含範例與最佳做法。

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

相關技能