Flutter アニメーション
概要
Flutterでスムーズでパフォーマンスの高いアニメーションを作成するための、各ユースケースに適したアプローチを学びます。このスキルは、暗黙的アニメーションと明示的アニメーションの選択から、ヒーロー遷移やスタッガードアニメーションのような複雑なエフェクトの実装まで、完全なアニメーションワークフローをカバーします。
アニメーションタイプの決定木
要件に基づいて適切なアニメーションタイプを選択してください:
暗黙的アニメーション - 以下の場合に使用:
- 単一のプロパティ(色、サイズ、位置)をアニメーション化する場合
- アニメーションが状態変化によってトリガーされる場合
- 細かい制御が不要な場合
明示的アニメーション - 以下の場合に使用:
- アニメーションのライフサイクルを完全に制御する必要がある場合
- 複数のプロパティを同時にアニメーション化する場合
- アニメーションの状態変化に反応する必要がある場合
- カスタムアニメーションやトランジションを作成する場合
ヒーローアニメーション - 以下の場合に使用:
- 2つの画面間で要素を共有する場合
- 共有要素トランジションを作成する場合
- ユーザーが要素をルート間で「飛ばす」ことを期待する場合
スタッガードアニメーション - 以下の場合に使用:
- 複数のアニメーションを順次または重複して実行する場合
- リップルエフェクトやシーケンシャルリビールを作成する場合
- リストアイテムを順番にアニメーション化する場合
物理ベースアニメーション - 以下の場合に使用:
- アニメーションを自然/物理的に感じさせたい場合
- スプリングのような振る舞い、スクロールジェスチャー
- ドラッグ可能なインタラクション
暗黙的アニメーション
暗黙的アニメーションは、プロパティが変更されたときに自動的にアニメーションを処理します。コントローラーは不要です。
一般的な暗黙的ウィジェット
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(
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(),
),
),
);
},
),
);
ラジアルヒーローアニメーション
トランジション中に円から長方形に変形:
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);
}
ヒーローのベストプラクティス
- 一意で一貫性のあるタグを使用(多くの場合、データオブジェクトそのもの)
- ルート間でヒーローウィジェットツリーを類似させる
- 「ポップ」エフェクトのために、画像を透明色の
Materialでラップ - トランジションのデバッグには
timeDilationを使用 - 必要に応じて
HeroModeを使用してヒーローアニメーションを無効化
スタッガードアニメーション
異なるタイミングで複数のアニメーションを実行します。
基本的なスタッガードアニメーション
すべてのアニメーションが1つのコントローラーを共有:
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,
);
}
}
Intervalベースのタイミング
各アニメーションには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, // 1秒あたりの単位
);
カスタム物理シミュレーション
_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を破棄
- リスナー内で
setState()の代わりにAnimatedBuilder/AnimatedWidgetを使用 - 自然な動きのために適切なカーブを選択
- アニメーションデバッグに
timeDilationを使用 - パフォーマンスを考慮(アニメーション構築で重いウィジェットを避ける)
- 様々なデバイスでアニメーションをテスト
- 直感的な操作感のためにリバースアニメーションをサポート
避けるべきこと
AnimationControllerの破棄を忘れる(メモリリーク)AnimatedBuilderで十分な場合にアニメーションリスナーでsetState()を使用- アニメーションが即座に完了すると仮定する(
AnimationStatusを処理) - 過剰なアニメーション(アニメーションはユーザーの気を散らす可能性がある)
- 「ぎくしゃくした」感じのアニメーションを作成する(スムーズなカーブを使用)
- アクセシビリティを無視する(
disableAnimations設定を尊重)
リソース
references/
implicit.md - 暗黙的アニメーションウィジェットの完全なリファレンス(例とベストプラクティス付き)。
explicit.md - 明示的アニメーション、AnimationController、パターンの詳細な解説。
hero.md - ヒーローアニメーションガイド(標準およびラジアルトランジション)。
staggered.md - スタッガードアニメーションパターンとタイミング戦略。
physics.md - 物理ベースアニメーションとシミュレーション。
curves.md - Curvesクラスのリファレンスと適切なカーブの選択方法。
(以降、翻訳のため省略)