Flutter のアニメーション

1. はじめに

アニメーションは、アプリのユーザー エクスペリエンスを向上させ、重要な情報をユーザーに伝え、アプリをより洗練された楽しいものにするための優れた方法です。

作成するアプリの概要

この Codelab では、Google Antigravity と協力して、さまざまな Flutter アニメーション効果とテクニックを駆使した多肢選択式のクイズゲームを作成します。

完成した Flutter クイズアプリのアニメーション録画。アニメーション化されたスコアボードの星、スライドする質問カード、3D で反転する回答カード、コンテナの遷移が表示されています。

Antigravity を使用して、エージェントに次のプロンプトを繰り返し入力します。

  • 暗黙的なアニメーション、トゥイーン、イージング カーブを使用してサイズと色をアニメーション化するスコアボード ウィジェットを作成します。
  • AnimatedSwitcher 内で明示的な SlideTransition 効果と FadeTransition 効果を使用して、質問の遷移をアニメーション化します。
  • AnimationController で駆動し、TweenSequence でスタッガードされたカスタム 3D カードフリップ エフェクトを作成します。
  • animations パッケージのビルド済みマテリアル モーション遷移(FadeThroughTransition と OpenContainer)を使用し、Android の予測型「戻る」ジェスチャーのサポートを追加します。

Flutter のアニメーション フレームワークの概要

Flutter は、各フレームでウィジェット ツリーの一部を再構築することで、アニメーション効果を表示します。事前に構築されたアニメーション効果とコンポーザブル API が用意されているため、アニメーションの作成と調整を簡単に行うことができます。

  • 暗黙的なアニメーションは、アニメーション全体を自動的に実行する、事前構築済みのアニメーション効果です。アニメーションのターゲット値が変更されると、ウィジェットは現在の値からターゲット値までスムーズにアニメーション化され、その間の各値が表示されます。AnimatedSize、AnimatedScale、AnimatedPositioned などがあります。
  • 明示的なアニメーションは、Animation オブジェクトを使用して進行状況を制御する、事前作成済みのアニメーション効果です。SizeTransition、ScaleTransition、SlideTransition、FadeTransition などがあります。
  • Animation は、実行中または停止中のアニメーションを表すクラスです。現在の value と status を公開し、Listenable を拡張して、アニメーションの進行に合わせてリスナーに通知します。
  • AnimationController は Animation を作成し、そのライフサイクルを制御します。forward()、reset()、stop()、repeat() などのメソッドは、レンダリングされる視覚効果とは無関係に再生を制御します。
  • トゥイーンは、begin 値と end 値の間の値を補間し、double、Offset、Color などの任意の型を表すことができます。
  • カーブは、パラメータの変化率を時間の経過とともに調整します。イージング曲線を適用すると、アニメーションが自然に加速または減速します。曲線は、0.0~1.0 の入力値を出力値にマッピングします。

学習の流れ

この Codelab では、クイズアプリを作成してアニメーション化する手順を段階的に説明します。

  1. Flutter 環境をセットアップする - ターゲット プラットフォーム用に Flutter SDK と Google Antigravity を構成します。
  2. プロジェクトを作成する - Model-View-ViewModel(MVVM)パターンで構成された多肢選択式クイズアプリをスキャフォールディングするよう Antigravity に指示します。
  3. 暗黙的なアニメーション効果を使用する - AnimatedScale、TweenAnimationBuilder、Curves.elasticOut を使用してスケールと色をアニメーション化する星ベースの Scoreboard を追加します。
  4. 明示的なアニメーション効果を使用する - AnimatedSwitcher、SlideTransition、FadeTransition、およびカスタム layoutBuilder を使用して、受信および送信の質問をアニメーション化します。
  5. アニメーションの状態を制御する - AnimationController、AnimatedBuilder、Transform、スタッガード TweenSequence を使用して、カスタム 3D CardFlipEffect を作成します。
  6. カスタム ナビゲーション遷移を使用する - PredictiveBackPageTransitionsBuilder を使用して PageTransitionsTheme を追加し、PageTransitionSwitcher と FadeThroughTransition を使用して質問を切り替え、OpenContainer を使用してゲームオーバー画面に展開します。

学習内容

  • Google Antigravity と連携して、リッチなアニメーションを備えた Flutter アプリを反復的に構築、カスタマイズする方法。
  • 暗黙的にアニメーション化されたウィジェット(AnimatedScale と TweenAnimationBuilder)を使用して、最小限のコードで洗練されたアニメーションを実現する方法。
  • Animation オブジェクトによって駆動される明示的にアニメーション化されたウィジェット(SlideTransition と FadeTransition)を作成する方法。
  • AnimationController と TweenSequence を使用して、スタッガード 3D ウィジェット遷移を構築する方法。
  • animations パッケージと PredictiveBackPageTransitionsBuilder を使用して、マテリアル モーションと Android の予測型「戻る」遷移を実現する方法。

前提条件

  • Flutter ウィジェットと Dart 構文に関する基本的な知識。

2. Flutter 環境をセットアップする

編集者

この Codelab では、AI ファーストの開発環境として Google Antigravity を使用します。各ステップでは、Antigravity にプロンプトを入力してアプリのコンポーネントを生成または進化させ、生成されたコードで Flutter アニメーションの重要なコンセプトを確認します。また、必要に応じてクリエイティブなバリエーションを試すこともできます。

開発ターゲットを選ぶ

この Codelab は、次のいずれかのターゲット プラットフォームで実行できます。

  • Android の実機またはエミュレータ(ナビゲーション遷移のステップで予測型「戻る」ジェスチャーをテストする場合に推奨)。
  • iOS 実機または iOS シミュレータ(macOS 上の Xcode が必要)。
  • ウェブブラウザ(Chrome など)。
  • Windows、macOS、Linux のデスクトップ ターゲット。

Flutter をインストールする

Flutter SDK の最新のインストール手順は、常に docs.flutter.dev にあります。

Flutter のウェブサイトでは、SDK、プラットフォーム固有のツール、エディタ プラグインのインストールについて説明されています。この Codelab では、次のソフトウェアをインストールします。

  1. Flutter SDK
  2. 公式の Dart プラグインと Flutter プラグインが有効になっている Google Antigravity(プラグイン マーケットプレイスの [Build with Google] セクションで入手可能)。
  3. 選んだ開発ターゲット用のコンパイラ ソフトウェア(たとえば、Android がターゲットなら Android Studio、Windows がターゲットなら Visual Studio、macOS または iOS がターゲットなら Xcode)。

次のステップでは、Antigravity にプロンプトを送信して、Flutter プロジェクトを作成し、クイズ スターター アプリをスキャフォールディングします。

3. プロジェクトを作成する

プロジェクトを作成するよう Antigravity に指示する

  1. Google Antigravity を起動し、プロジェクトをビルドする空のディレクトリを開きます(ホーム ディレクトリ内のフォルダや C:\src\ など、権限昇格を必要とせず、スペースを含まないパスを選択します)。
  2. Antigravity エージェントのチャットパネルで、次のプロンプトを送信して Flutter プロジェクトを作成し、animations と material_ui の依存関係を追加して、MVVM クイズアプリをスキャフォールディングします。
Create a new empty Flutter project named `quiz` for a multiple-choice Flutter animations quiz game and add the `animations` and `material_ui` packages. Using `package:material_ui/material_ui.dart`, create `lib/model.dart` with `Question` (`question`, `possibleAnswers`, `correctAnswer`) and `QuestionBank` (`hasNextQuestion`, `remainingQuestions`, `getRandomQuestion()`) populated with three multiple-choice questions about Flutter animations. Create `lib/view_model.dart` with `QuizViewModel extends ChangeNotifier` (`onGameOver` callback, `totalQuestions`, `currentQuestion`, `answeredQuestionCount`, `score`, `didAnswerQuestion`, `hasNextQuestion`, `getNextQuestion()`, and `checkAnswer(int)`). Create `lib/home_screen.dart` (`HomeScreen` with a "New Game" button that pushes `QuestionScreen`), `lib/question_screen.dart` (`QuestionScreen` listening to `QuizViewModel` using `ListenableBuilder`, showing a game-over `AlertDialog` that pops to the first route, plus `QuestionCard`, a 2-column `AnswerCards` grid using `Card.filled` with `ValueKey(answers[index])` that highlights the `correctAnswer` in `tertiaryContainer`, and `StatusBar`), and wire `HomeScreen` up in `lib/main.dart` inside `MainApp` with a blue Material 3 `ColorScheme.fromSeed`.

生成されたコードを理解する

Antigravity は、Model-View-ViewModel(MVVM)パターンで構成された 2 つの画面からなる多肢選択式のクイズゲームをスキャフォールディングします。

  • lib/main.dart - マテリアル 3 テーマ設定(package:material_ui/material_ui.dart)を使用して MaterialApp を構成し、HomeScreen を起動します。
  • lib/home_screen.dart - QuestionScreen に移動する [New Game] ボタンを含むタイトル画面を表示します。
  • lib/model.dart - Question データクラスと QuestionBank を定義します。は、バンクが空になるまでランダムに質問を抽出します。
  • lib/view_model.dart - QuizViewModel を定義します。これは、現在の問題、プレーヤーのスコア、ゲームオーバー状態を追跡する ChangeNotifier です。
  • lib/question_screen.dart - QuestionScreen(ビュー)をレンダリングします。これは QuizViewModel をリッスンし、QuestionCard、AnswerCards、StatusBar をコンポーズします。

QuizViewModel と ListenableBuilder を使用したリアクティブな状態

lib/view_model.dart では、QuizViewModel が ChangeNotifier を拡張し、ユーザーが回答を選択するか、次の質問に進むたびに notifyListeners() を呼び出します。

class QuizViewModel extends ChangeNotifier {
  final QuestionBank _questionBank = QuestionBank();
  final VoidCallback onGameOver;
  late final int totalQuestions;
  Question? currentQuestion;
  int answeredQuestionCount = 0;
  int score = 0;
  bool didAnswerQuestion = false;
  bool get hasNextQuestion => answeredQuestionCount < totalQuestions;
  // ...

lib/question_screen.dart では、QuestionScreen が Scaffold を ListenableBuilder でラップするため、viewModel がリスナーに通知するたびに UI が自動的に再ビルドされます。

@override
Widget build(BuildContext context) {
  return ListenableBuilder(
    listenable: viewModel,
    builder: (context, child) {
      return Scaffold(
        // ...

アプリを実行してテストする

選択した対象デバイスでアプリを実行し、スターター プロジェクトが想定どおりに動作することを確認します。

HomeScreen と QuestionScreen が並べて表示されているスターター Flutter クイズアプリ

[New Game] をタップして、いくつかの質問に答えます。現時点では、アプリはスコアテキスト、問題カード、解答カードをアニメーション効果なしで即座に更新します(Navigator のデフォルトのルート遷移を除く)。次のステップでは、スコアボードに暗黙的なアニメーションを追加します。

4. 暗黙的なアニメーション効果を使用する

暗黙的アニメーションは、内部のアニメーション状態を自動的に管理するため、Flutter アプリにモーションを追加する最も簡単な方法であることがよくあります。ターゲット プロパティ(scale、opacity、padding など)が変更されるたびに、ImplicitlyAnimatedWidget は、指定された duration にわたって古い値から新しい値にスムーズに補間します。

このステップでは、書式なしテキストのステータスバーを、星ベースの Scoreboard に置き換えます。この は、プレーヤーが得点したときに各星のスケールと色の両方をアニメーション化します。

スコアボードの星が跳ねて、灰色から黄色に変わる様子を示す GIF アニメーション

Antigravity に、アニメーション化された星のスコアボードを追加するよう指示する

Antigravity で次のプロンプトを送信して lib/scoreboard.dart を作成し、StatusBar に統合します。

Create `lib/scoreboard.dart` (importing `package:material_ui/material_ui.dart`) with a `Scoreboard` widget (`score` and `totalQuestions`) that renders a row of `AnimatedStar` widgets (`isActive: score > i`), and replace the text children in `StatusBar` (`lib/question_screen.dart`) with `Scoreboard`. In `AnimatedStar`, animate each 50px `Icons.star` over 1000ms using `Curves.elasticOut`: wrap the icon in an `AnimatedScale` (scaling from `0.5` when inactive to `1.0` when active) and a `TweenAnimationBuilder<Color?>` using a `ColorTween` from `Colors.grey.shade400` to `Colors.yellow.shade700` when active.

生成されたコードを理解する

AnimatedScale を使用した暗黙的なスケーリング

lib/scoreboard.dart では、Scoreboard がクイズの質問ごとに 1 つの AnimatedStar を表示し、isActive: score > i を渡します。AnimatedStar 内で、isActive が true になると、AnimatedScale は子を 0.5 から 1.0 にスケーリングします。

return AnimatedScale(
  scale: isActive ? 1.0 : 0.5,
  curve: _curve,
  duration: _duration,
  // ...

静的な Icon 色で AnimatedScale のみを使用した場合、星のサイズはスムーズにアニメーション化されますが、色はグレーから黄色に瞬時に切り替わります。

星がスムーズに拡大縮小し、色がすぐに変化する様子を示す GIF アニメーション

TweenAnimationBuilder と ColorTween を使用した色の補間

星のスケールに合わせて色をアニメーション化するには、AnimatedContainer(コンテナの装飾をアニメーション化する)または AnimatedIcon(AnimatedIcons で事前定義されたアイコンペア間でモーフィングする)の使用を検討してください。ただし、どちらも標準の Icons.star ウィジェットの色をアニメーション化するものではありません。

代わりに、生成されたコードは TweenAnimationBuilder を使用します。これは、Tween を使用して任意のプロパティをアニメーション化する、汎用性の高い ImplicitlyAnimatedWidget です。Tween は、begin 値と end 値を受け取り、アニメーションのタイムライン全体の中間値を計算します。ここで、ColorTween は、非アクティブなグレーとアクティブな黄色の間で補間します。

child: TweenAnimationBuilder(
  curve: _curve,
  duration: _duration,
  tween: ColorTween(
    begin: _deactivatedColor,
    end: isActive ? _activatedColor : _deactivatedColor,
  ),
  builder: (context, value, child) {
    return Icon(Icons.star, size: 50, color: value);
  },
),

isActive に基づいて Tween.end が変更されるたびに、TweenAnimationBuilder は現在の値から新しい end 値に自動的にアニメーション化されます。アニメーションの実行中に isActive が変更された場合も同様です。

星のサイズと色がスムーズに変化する GIF アニメーション

Curves.elasticOut を使用してイージング カーブを適用する

一定の線形速度で実行されるアニメーションは、機械的に感じられることがあります。Curve は、時間の経過とともに変化率を変化させるイージング関数を適用し、0.0 と 1.0 の間の入力進行状況値(X 軸)を出力値(Y 軸)にマッピングします。Flutter には、Curves クラスに事前ビルドされたカーブの豊富なカタログが含まれています。たとえば、Curves.easeIn や Curves.easeOut などです。

Curves.easeIn イージング関数のグラフ。初期の進行が遅く、1.0 に向かって加速することを示しています。Curves.easeOut イージング関数のグラフ。最初は進行が速く、1.0 に向かって減速します。

AnimatedScale と TweenAnimationBuilder の両方に Curves.elasticOut を渡すと、オーバーシュートして最後に落ち着く、エネルギッシュなスプリング効果が得られます。

Curves.elasticOut イージング関数のグラフ。振動するスプリング曲線が 1.0 に収束することを示しています。

アプリを実行してテストする

アプリをホットリロードして、問題に正しく答えると、StatusBar で星が跳ねて金色に光ります。

DevTools を使用して、遅いアニメーションを検査する

高速なアニメーションをフレームごとに検査するために、Flutter DevTools には [Slow animations] の切り替えボタンが用意されています。このボタンを使用すると、アプリ内のすべてのアニメーションの速度が 5 分の 1 に低下します。デバッグモードで実行中に DevTools で Flutter Inspector を開き、ツールバーの [Slow animations] ボタンをクリックします。

Flutter DevTools Widget Inspector ツールバーの [Slow animations] ボタンがハイライト表示されている

5. 明示的なアニメーション効果を使用する

明示的アニメーションは、暗黙的アニメーションと同様に、事前構築済みのアニメーション ウィジェットですが、ターゲット値ではなく、Animation オブジェクトをパラメータとして受け取ります。そのため、Animation が親ウィジェット(AnimatedSwitcher、ルート遷移、独自の AnimationController など)によって提供される場合や、複数の遷移を組み合わせる場合に最適です。

このステップでは、新しい質問がレイアウトに飛び込むことなく、スムーズにスライドしてフェードインするように QuestionCard をアニメーション化します。

質問の遷移をアニメーション化するよう Antigravity に指示する

Antigravity で次のプロンプトを送信して、lib/question_screen.dart の QuestionCard を更新します。

Update `QuestionCard` in `lib/question_screen.dart` to wrap its `Card` (keyed by `ValueKey(question)`) in an `AnimatedSwitcher` with a 300ms duration. Configure `transitionBuilder` to apply `Curves.easeInCubic` using `CurveTween` and compose a `FadeTransition` with a `SlideTransition` that slides from `Offset(-0.1, 0.0)` to `Offset.zero`. Override `layoutBuilder` to return a `Stack` aligned to `Alignment.topCenter` so the card doesn't jump vertically when switching questions.

生成されたコードを理解する

AnimatedSwitcher で SlideTransition と FadeTransition を作成する

AnimatedSwitcher は、child が異なる Key を持つウィジェットに変更されるたびに、自動的に遷移を実行します。

デフォルトでは、AnimatedSwitcher は古い子と新しい子の間でクロスフェードしますが、transitionBuilder コールバックは、受信と送信の child ウィジェットと Animation を提供するため、カスタムの明示的なアニメーションを構築できます。

lib/question_screen.dart では、生成された transitionBuilder は、FadeTransition でラップされた SlideTransition(Animation が必要)を使用します。

transitionBuilder: (child, animation) {
  final curveAnimation = CurveTween(
    curve: Curves.easeInCubic,
  ).animate(animation);
  final offsetAnimation = Tween<Offset>(
    begin: const Offset(-0.1, 0.0),
    end: Offset.zero,
  ).animate(curveAnimation);
  final fadeInAnimation = curveAnimation;
  return FadeTransition(
    opacity: fadeInAnimation,
    child: SlideTransition(position: offsetAnimation, child: child),
  );
},

すべての Tween には、入力 Animation を、そのトゥイーンが適用された新しい Animation に変換する animate() メソッドが用意されています。Animation.drive() を使用して、トゥイーンを簡潔に連結することもできます。

final offsetAnimation = animation
    .drive(CurveTween(curve: Curves.easeInCubic))
    .drive(Tween<Offset>(begin: const Offset(-0.1, 0.0), end: Offset.zero));

layoutBuilder を使用してレイアウトのジャンプを防ぐ

カスタムの layoutBuilder がないと、AnimatedSwitcher は遷移の実行中に子を Stack の中央に配置し、アニメーションが終了するとカードを使用可能なスペースの上部に戻します。

遷移が終了すると QuestionCard が Stack の中央から上部にジャンプする様子を示す GIF アニメーション

layoutBuilder をオーバーライドして Alignment.topCenter を使用すると(AnimatedSwitcher.defaultLayoutBuilder で使用される Alignment.center ではなく)、遷移全体で、入ってくるカードと出ていくカードが上部で揃えられます。

layoutBuilder: (currentChild, previousChildren) {
  return Stack(
    alignment: Alignment.topCenter,
    children: <Widget>[
      ...previousChildren,
      ?currentChild,
    ],
  );
},

アプリを実行してテストする

アプリをホットリロードし、質問に回答して [Next] をタップし、新しい QuestionCard が画面上部でスムーズにスライドしてフェードインすることを確認します。

学習した主なコンセプト

  • 明示的なアニメーション ウィジェットは、単一のターゲット値と期間ではなく、Animation オブジェクトを受け取ります。
  • Animation クラスは、特定の視覚プロパティに関連付けられることなく、時間の経過に伴うアニメーションの進行状況を表します。
  • Tween.animate() と Animation.drive() は、CurveTween を変換して Animation に適用します。
  • AnimatedSwitcher.layoutBuilder は、遷移中に受信子と送信子をどのように配置するかをカスタマイズします。

6. アニメーションの状態を制御する

ここまでは、Flutter がすべてのアニメーションの再生を管理していました。アニメーションの開始、停止、リセット、複数のフェーズのシーケンスを完全に制御する必要がある場合は、AnimationController を使用して独自の Animation を作成できます。

このステップでは、カスタムの CardFlipEffect ウィジェットを作成します。このウィジェットは、質問が変わると各回答カードを 3D で反転させます。TweenSequence を使用して 4 枚のカードをずらし、1 枚ずつ反転させます。

Antigravity にプロンプトを入力して、3D カードを時間差で反転させるエフェクトを作成する

Antigravity で次のプロンプトを送信して lib/flip_effect.dart を作成し、回答カードを lib/question_screen.dart でラップします。

Create `lib/flip_effect.dart` with a stateful `CardFlipEffect` widget (`child`, `duration`, and `delayAmount`) using `SingleTickerProviderStateMixin`. When `widget.child.key` changes in `didUpdateWidget`, store the previous child and run an `AnimationController` whose duration is `widget.duration * (widget.delayAmount + 1)` (resetting when it reaches `1`). Drive the controller through a `TweenSequence<double>` (`_animationWithDelay`) that holds at `0.0` with `ConstantTween` for weight `delayAmount` (when `delayAmount > 0`) and then interpolates from `0.0` to `1.0` with weight `1.0`, using `AnimatedBuilder` and `Transform` (`Matrix4.identity()..rotateX(_animationWithDelay.value * math.pi)`) to show `_previousChild` for the first half of the flip and `Transform.flip(flipY: true, child: child)` for the second half. In `AnswerCards` (`lib/question_screen.dart`), wrap each `Card.filled` in `CardFlipEffect` with a 300ms duration and `delayAmount: index.toDouble() / 2`.

生成されたコードを理解する

AnimationController を使用したアニメーション ライフサイクルの管理

AnimationController を使用してカスタム アニメーションを作成する手順は次の 4 つです。

  1. StatefulWidget(CardFlipEffect)を作成します。
  2. SingleTickerProviderStateMixin を State クラスにミックスインして、フレーム Ticker を提供できるようにします。
  3. initState() の AnimationController を vsync: this で初期化し、widget.child.key が変更されるたびに didUpdateWidget() の forward() をトリガーします。
  4. AnimatedBuilder を使用して、ティックごとにウィジェット ツリーを再ビルドします。

AnimatedBuilder と Transform を使用した 3D 回転

2D 回転の場合、Flutter には AnimatedRotation(暗黙的)と RotationTransition(明示的)が用意されています。3D X 軸カードフリップでは、Matrix4 変換と、フリップの途中で前面ウィジェットと背面ウィジェットを入れ替える(value < 0.5)ことが必要になるため、CardFlipEffect は AnimatedBuilder と Transform を組み合わせます。

@override
Widget build(BuildContext context) {
  return AnimatedBuilder(
    animation: _animationWithDelay,
    builder: (context, child) {
      return Transform(
        alignment: Alignment.center,
        transform: Matrix4.identity()
          ..rotateX(_animationWithDelay.value * math.pi),
        child: _animationController.isAnimating
            ? _animationWithDelay.value < 0.5
                  ? _previousChild
                  : Transform.flip(flipY: true, child: child)
            : child,
      );
    },
    child: widget.child,
  );
}

回転の前半(_animationWithDelay.value < 0.5)では、ウィジェットに _previousChild が表示されます。カードが 90 度を超えて回転すると、新しい child が垂直方向に反転(Transform.flip(flipY: true))して表示され、$\pi$ ラジアンで回転が完了すると、テキストが正しい向きで表示されます。

次の質問に進むときに、回答カードが 3D で反転する様子を示す GIF アニメーション。

TweenSequence を使用したアニメーションのスタッガリング

CardFlipEffect は、dart:async の Future.delayed を使用してカードをずらして配置しているわけではありません。TweenSequence を使用してアニメーション タイムライン内に遅延を保持すると、スタッガード効果全体が同じ TickerProvider によって駆動されます。そのため、Flutter DevTools で [Slow animations] を有効にすると、遅延も比例して遅くなります。

lib/flip_effect.dart では、_animationWithDelay は 2 つの TweenSequenceItem を連結します。delayAmount で重み付けされた ConstantTween(0.0) の後に、1.0 で重み付けされた Tween(begin: 0.0, end: 1.0) が続きます。

_animationWithDelay = TweenSequence<double>([
  if (widget.delayAmount > 0)
    TweenSequenceItem(
      tween: ConstantTween<double>(0.0),
      weight: widget.delayAmount,
    ),
  TweenSequenceItem(tween: Tween(begin: 0.0, end: 1.0), weight: 1.0),
]).animate(_animationController);

AnswerCards(lib/question_screen.dart)で delayAmount: index.toDouble() / 2 を渡すと、グリッド内の各カードが反転するまでの初期ホールド時間が徐々に長くなります。

return CardFlipEffect(
  delayAmount: index.toDouble() / 2,
  duration: const Duration(milliseconds: 300),
  child: Card.filled(
    key: ValueKey(answers[index]),
    // ...

アプリを実行してテストする

ホット リスタートを実行し、質問に答えて [次へ] をタップすると、4 つの回答カードが 1 つずつ裏返ります。

4 つの回答カードが時間差で 1 つずつ裏返る様子を示す GIF アニメーション

7. カスタム ナビゲーション遷移を使用する

1 つの画面内でウィジェットをアニメーション化するだけでなく、画面と主要な UI 状態の間の遷移をアニメーション化することもできます。このステップでは、pub.dev の公式 animations パッケージ(FadeThroughPageTransitionsBuilder、PageTransitionSwitcher、FadeThroughTransition、OpenContainer)のビルド済みマテリアル モーション ウィジェットを使用して、Android の予測型「戻る」ジェスチャーを有効にします。

Antigravity にプロンプトを入力して、マテリアル モーションと予測型「戻る」遷移を追加する

Antigravity で次のプロンプトを送信して、lib/main.dart と lib/question_screen.dart を更新します。

Using `package:animations/animations.dart`, update `ThemeData` in `lib/main.dart` with a `PageTransitionsTheme` that uses `PredictiveBackPageTransitionsBuilder()` on Android and `FadeThroughPageTransitionsBuilder()` on iOS, macOS, Windows, and Linux. In `lib/question_screen.dart`, create a `GameOverScreen` widget displaying `Scoreboard`, "You Win!", the final score, and an "OK" button that pops back to the first route. Update `QuestionCard` to use `PageTransitionSwitcher` (200ms duration) with `FadeThroughTransition` wrapping an `OpenContainer` (`key: ValueKey(question)`, `tappable: false`, `closedColor: Color(0xfff2f3fa)`, 12px rounded corners, elevation 4) whose `closedBuilder` registers `openContainer` using `onChangeOpenContainer` and renders the question text, and whose `openBuilder` returns `GameOverScreen(viewModel: viewModel)` when `_handleGameOver` invokes the stored callback.

生成されたコードを理解する

カスタムルート遷移と Android の予測型「戻る」

1 つのナビゲーション呼び出しをカスタマイズする場合は、PageRouteBuilder を Navigator.push() に渡し、プライマリ animation と secondaryAnimation の両方を受け取る transitionsBuilder(FadeTransition や FadeThroughTransition など)を指定します。

アプリ全体で一貫したルート遷移を適用し、Android の予測型「戻る」ジェスチャーをサポートするには、アプリの ThemeData(lib/main.dart)で pageTransitionsTheme を構成します。

theme: ThemeData(
  colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
  pageTransitionsTheme: const PageTransitionsTheme(
    builders: {
      TargetPlatform.android: PredictiveBackPageTransitionsBuilder(),
      TargetPlatform.iOS: FadeThroughPageTransitionsBuilder(),
      TargetPlatform.macOS: FadeThroughPageTransitionsBuilder(),
      TargetPlatform.windows: FadeThroughPageTransitionsBuilder(),
      TargetPlatform.linux: FadeThroughPageTransitionsBuilder(),
    },
  ),
),

Android の GIF アニメーション。ユーザーが画面の端からドラッグして、QuestionScreen の背後にある HomeScreen を覗き見している様子を示しています。

予測型「戻る」を使用すると、Android ユーザーは画面の端からスワイプして、戻る操作を確定する前に前のルートをプレビューできます。PredictiveBackPageTransitionsBuilder は、Android 14(API 34)以降でシステムの予測型「戻る」ジェスチャーをリッスンし、以前の Android バージョンでは ZoomPageTransitionsBuilder に適切にフォールバックします。プラットフォームの構成の詳細については、Android の予測型「戻る」ガイドをご覧ください。

PageTransitionSwitcher と FadeThroughTransition の切り替えに関する質問

標準の AnimatedSwitcher は、transitionBuilder で 1 つの Animation のみを公開します。FadeThroughTransition などのマテリアル モーション遷移は、受信 animation と送信 secondaryAnimation の両方を調整するため、QuestionCard は animations パッケージの PageTransitionSwitcher を使用します。

return PageTransitionSwitcher(
  duration: const Duration(milliseconds: 200),
  transitionBuilder: (child, animation, secondaryAnimation) {
    return FadeThroughTransition(
      animation: animation,
      secondaryAnimation: secondaryAnimation,
      child: child,
    );
  },
  // ...

OpenContainer を使用したコンテナ変換

OpenContainer が、閉じたカード ウィジェットを全画面表示の開いたウィジェットに展開

OpenContainer ウィジェットは、マテリアルのコンテナ変換パターンを実装し、小さなウィジェット(closedBuilder)を全画面のデスティネーション(openBuilder)にスムーズに拡大します。

lib/question_screen.dart では、QuestionCard が tappable: false を含む OpenContainer をレンダリングするため、質問カード自体をタップしてもゲームは終了しません。代わりに、closedBuilder は openContainer コールバックを _QuestionScreenState に渡し、は最後の質問に回答したときにそれを呼び出します。

child: OpenContainer(
  key: ValueKey(question),
  tappable: false,
  closedColor: _backgroundColor,
  closedShape: const RoundedRectangleBorder(
    borderRadius: BorderRadius.all(Radius.circular(12.0)),
  ),
  closedElevation: 4,
  closedBuilder: (context, openContainer) {
    onChangeOpenContainer(openContainer);
    return ColoredBox(
      color: _backgroundColor,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Text(
          question ?? '',
          style: Theme.of(context).textTheme.displaySmall,
        ),
      ),
    );
  },
  openBuilder: (context, closeContainer) {
    return GameOverScreen(viewModel: viewModel);
  },
),

アプリを実行してテストする

アプリをホットリスタートし、新しいゲームを開始して、3 つの質問すべてに回答します。最後の質問に回答すると、OpenContainer は質問カードを全画面表示の GameOverScreen にスムーズに拡大します。

OpenContainer を使用して QuestionCard が全画面の GameOverScreen に展開される様子を示す GIF アニメーション。

8. 完了

おめでとうございます!Google Antigravity と協力して、Flutter クイズアプリにリッチなアニメーション効果を追加し、Flutter のアニメーション システムのコア ビルディング ブロックについて学びました。

作成したもの

  • 暗黙的なアニメーション スコアボード: AnimatedScale と TweenAnimationBuilder を ColorTween と Curves.elasticOut とともに使用して、プレーヤーがスコアを獲得したときに星アイコンをアニメーション化しました。
  • 明示的な質問の遷移: AnimatedSwitcher 内に FadeTransition と SlideTransition を作成し、layoutBuilder を上揃えにしました。
  • 3D カードの段階的な反転: AnimationController、AnimatedBuilder、TweenSequence の遅延を使用して、3D Matrix4 回転を制御しました。
  • マテリアル モーションと予測型「戻る」: PredictiveBackPageTransitionsBuilder と FadeThroughPageTransitionsBuilder を使用して PageTransitionsTheme を構成し、animations パッケージの PageTransitionSwitcher と OpenContainer を使用しました。

すべてのアニメーション効果が有効になっている、完成した Flutter クイズアプリのアニメーション録画。

次のステップ

以下の関連する Codelab をご覧ください。

関連情報

docs.flutter.dev で、アニメーションのガイドとレシピをさらに確認する。

リファレンス ドキュメント