Flutter 中的動畫

1. 簡介

動畫是提升應用程式使用者體驗、向使用者傳達重要資訊,以及讓應用程式更精緻、更實用的絕佳方式。

建構項目

在本程式碼實驗室中,您將與 Google Antigravity 合作,打造一款選擇題測驗遊戲,其中包含多種 Flutter 動畫效果和技術。

完成的 Flutter 測驗應用程式動畫錄製,顯示動畫計分板星星、滑動問題卡、3D 翻轉答案卡和容器轉換。

您將使用 Antigravity,反覆提示代理執行下列操作:

  • 使用隱式動畫、補間動畫和加/減速曲線,建構會變更大小和顏色動畫的計分板小工具。
  • 在 AnimatedSwitcher 中使用明確的 SlideTransition 和 FadeTransition 效果,為問題轉換加上動畫效果。
  • 建立由 AnimationController 驅動的自訂 3D 卡片翻轉效果,並使用 TweenSequence 錯開。
  • 使用 animations 套件中預先建構的 Material 動作轉場效果 (FadeThroughTransition 和 OpenContainer),並新增 Android 的預測返回手勢支援。

Flutter 動畫框架總覽

Flutter 會在每個影格上重建部分小工具樹狀結構,藉此顯示動畫效果。這個程式庫提供預建動畫效果和可組合 API,可讓您輕鬆建立及協調動畫:

  • 隱含動畫是預先建構的動畫效果,會自動執行整個動畫。當動畫的「目標」值變更時,小工具會流暢地從目前值轉換為目標值,並顯示兩者之間的所有值。例如 AnimatedSize、AnimatedScale 和 AnimatedPositioned。
  • 明確動畫是預先建構的動畫效果,會使用 Animation 物件來驅動進度。例如 SizeTransition、ScaleTransition、SlideTransition 和 FadeTransition。
  • Animation 類別代表執行中或已停止的動畫。這個類別會公開目前的值和狀態、擴充 Listenable,並在動畫播放時通知事件監聽器。
  • AnimationController 會建立 Animation 並控管其生命週期。forward()、reset()、stop() 和 repeat() 等方法可控制播放,不受轉譯的視覺效果影響。
  • 補間動畫會插補 begin 和 end 之間的值,並可代表任何類型,例如 double、Offset 或 Color。
  • 曲線會調整參數隨時間變化的速率。套用加/減速曲線,可讓動畫自然加速或減速。曲線會將介於 0.0 和 1.0 之間的輸入值對應至輸出值。

學習旅程

本程式碼實驗室會逐步引導您建構測驗應用程式並加入動畫:

  1. 設定 Flutter 環境:為目標平台設定 Flutter SDK 和 Google Antigravity。
  2. 建立專案:提示 Antigravity 建立選擇題測驗應用程式的鷹架,並採用 Model-View-ViewModel (MVVM) 模式。
  3. 使用隱含動畫效果:新增星形 Scoreboard,並使用 AnimatedScale、TweenAnimationBuilder 和 Curves.elasticOut 建立縮放和顏色動畫。
  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 提供 Material 動作和 Android 預測返回轉場效果。

必要條件

  • 對 Flutter 小工具和 Dart 語法有基本瞭解。

2. 設定 Flutter 環境

編輯者

本程式碼實驗室會使用 Google Antigravity 做為 AI 優先開發環境。在每個步驟中,您會提示 Antigravity 生成或改良應用程式元件、查看生成程式碼中的重要 Flutter 動畫概念,並視需要探索創意變化版本。

選擇開發目標

您可以在下列任一目標平台上執行這個程式碼實驗室:

  • Android 實體裝置或模擬器 (建議用於測試導覽轉場步驟中的預測返回手勢)。
  • iOS 實體裝置或 iOS 模擬器 (macOS 須安裝 Xcode)。
  • 網路瀏覽器 (例如 Chrome)。
  • Windows、macOS 或 Linux 桌面目標。

安裝 Flutter

如需安裝 Flutter SDK 的最新操作說明,請前往 docs.flutter.dev。

Flutter 網站上的操作說明涵蓋安裝 SDK、平台專屬工具和編輯器外掛程式。請安裝下列軟體,以便進行本程式碼實驗室:

  1. Flutter SDK
  2. Google Antigravity,並啟用官方 Dart 和 Flutter 外掛程式 (可在外掛程式市集的「Build with Google」部分找到)。
  3. 所選開發目標的編譯器軟體 (例如,Android Studio 適用於 Android,Visual Studio 適用於 Windows,Xcode 適用於 macOS 或 iOS)。

在下一個步驟中,您將提示 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 會建立一個選擇題測驗遊戲,其中包含兩個採用模型-檢視-檢視模型 (MVVM) 模式結構的畫面:

  • lib/main.dart:使用 Material 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(
        // ...

執行及測試應用程式

在所選目標裝置上執行應用程式,確認範例專案是否正常運作。

Flutter 測驗入門應用程式,並排顯示 HomeScreen 和 QuestionScreen

輕觸「新遊戲」並回答幾個問題。目前,應用程式會立即更新分數文字、問題卡和答案卡,不含任何動畫效果 (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 會為測驗中的每個問題顯示一個 AnimatedStar,並傳遞 isActive: score > i。在 AnimatedStar 中,每當 isActive 變成 true 時,AnimatedScale 就會將子項從 0.5 縮放至 1.0:

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

如果只使用 AnimatedScale 搭配靜態 Icon 顏色,星星的大小會流暢地變化,但顏色會立即從灰色變成黃色:

GIF 動畫:星星流暢地縮放,顏色則立即變更

使用 TweenAnimationBuilder 和 ColorTween 插補顏色

如要同時為星星的顏色和大小加上動畫效果,可以考慮使用 AnimatedContainer (為容器裝飾加上動畫效果) 或 AnimatedIcon (在 AnimatedIcons 中預先定義的圖示組合之間變形)。不過,這兩者都無法為標準 Icons.star 小工具的顏色加上動畫效果。

而是會使用 TweenAnimationBuilder,這是一種多功能 ImplicitlyAnimatedWidget,可使用 Tween 為任何屬性建立動畫。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);
  },
),

每當 Tween.end 根據 isActive 變更時,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 減速。

將 Curves.elasticOut 同時傳遞至 AnimatedScale 和 TweenAnimationBuilder,會產生充滿活力的彈簧效果,在結束時會超出並穩定下來:

Curves.elasticOut 緩動函式的圖表,顯示振盪彈簧曲線穩定在 1.0。

執行及測試應用程式

熱重載應用程式並正確回答問題,即可在 StatusBar 中看到星星彈跳並發出金色光芒。

使用開發人員工具檢查緩慢的動畫

如要逐格檢查快速動畫,Flutter 開發人員工具提供「Slow animations」切換鈕,可將應用程式中的所有動畫速度放慢 5 倍。在偵錯模式下執行時,開啟開發人員工具中的 Flutter 檢查器,然後按一下工具列中的「Slow animations」按鈕:

Flutter 開發人員工具 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 會使用 SlideTransition (需要 Animation),並納入 FadeTransition:

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 都提供 animate() 方法,可將輸入 Animation 轉換為套用該補間動畫的新 Animation。您也可以使用 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,並在動畫結束後將資訊卡貼齊可用空間頂端:

GIF 動畫:顯示 QuestionCard 在轉場效果結束時,從 Stack 中心跳到頂端

覆寫 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 錯開四張卡片,讓卡片一張接一張翻轉。

提示 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 建立自訂動畫的步驟有四個:

  1. 建立 StatefulWidget (CardFlipEffect)。
  2. 將 SingleTickerProviderStateMixin 混入 State 類別,以便提供影格 Ticker。
  3. 使用 vsync: this 初始化 initState() 中的 AnimationController,並在 widget.child.key 變更時觸發 didUpdateWidget() 中的 forward()。
  4. 使用 AnimatedBuilder 在每個刻度上重新建構小工具樹狀結構。

使用 AnimatedBuilder 和 Transform 進行 3D 旋轉

Flutter 提供 AnimatedRotation (隱含) 和 RotationTransition (明確) 兩種 2D 旋轉方式。由於 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$ 弧度完成時,文字就會正面朝上:

GIF 動畫:顯示進入下一題時,答案卡會以 3D 方式翻轉。

使用 TweenSequence 錯開動畫

請注意,CardFlipEffect「不會」使用 dart:async 的 Future.delayed 錯開卡片。使用 TweenSequence 將延遲時間保留在動畫時間軸內,表示整個交錯效果是由同一個 TickerProvider 驅動,因此在 Flutter 開發人員工具中啟用「Slow animations」,也會按比例減慢延遲時間。

在 lib/flip_effect.dart 中,_animationWithDelay 會鏈結兩個 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]),
    // ...

執行及測試應用程式

執行熱重新啟動、回答問題,然後輕觸「Next」,即可看到四張答案卡逐一翻開。

GIF 動畫:四張答案卡以交錯延遲的方式逐一翻轉

7. 使用自訂導覽轉場效果

除了在單一畫面中為小工具加上動畫效果外,您也可以在畫面和主要 UI 狀態「之間」為轉場效果加上動畫。在這個步驟中,您將使用 pub.dev 上官方 animations 套件中預先建構的 Material 動作小工具 (FadeThroughPageTransitionsBuilder、PageTransitionSwitcher、FadeThroughTransition 和 OpenContainer),並啟用 Android 的預測返回手勢。

提示 Antigravity 新增 Material 動作和預測返回轉場效果

在 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 預測返回手勢

如要自訂單一導覽呼叫,您可以將 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 後方的主畫面。

Android 使用者可透過預測返回功能,從螢幕邊緣滑動並預覽上一個路徑,再決定是否返回。PredictiveBackPageTransitionsBuilder 會監聽 Android 14 (API 34) 以上版本的系統預測返回手勢,並在舊版 Android 上順利改用 ZoomPageTransitionsBuilder。如要瞭解平台設定詳情,請參閱 Android 預測返回手勢指南。

與PageTransitionSwitcher和FadeThroughTransition交換問題

標準 AnimatedSwitcher 只會在 transitionBuilder 中公開單一 Animation。由於 Material 動作轉換 (例如 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 小工具會實作 Material 的容器轉換模式,將較小的小工具 (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);
  },
),

執行及測試應用程式

熱重新啟動應用程式,開始新遊戲,並回答所有三個問題。回答最後一個問題時,OpenContainer 會順暢地將問題資訊卡展開為全螢幕 GameOverScreen:

GIF 動畫:顯示 QuestionCard 使用 OpenContainer 展開為全螢幕 GameOverScreen。

8. 恭喜

恭喜!您已與 Google Antigravity 合作,為 Flutter 測驗應用程式加入豐富的動畫效果,並探索 Flutter 動畫系統的核心建構模塊。

建構內容

  • 隱含動畫計分板:使用 AnimatedScale 和 TweenAnimationBuilder 搭配 ColorTween 和 Curves.elasticOut,在玩家得分時顯示星星圖示動畫。
  • 明確的問題轉換:在 AnimatedSwitcher 中組合 FadeTransition 和 SlideTransition,並將 layoutBuilder 靠上對齊。
  • 交錯 3D 卡片翻轉:使用 AnimationController、AnimatedBuilder 和 TweenSequence 延遲控制 3D Matrix4 旋轉。
  • Material 動態和預測返回:使用 PredictiveBackPageTransitionsBuilder 和 FadeThroughPageTransitionsBuilder 設定 PageTransitionsTheme,並使用 animations 套件中的 PageTransitionSwitcher 和 OpenContainer。

動畫錄製:已完成的 Flutter 測驗應用程式,已啟用所有動畫效果。

後續步驟

查看下列相關程式碼實驗室:

延伸閱讀

如要查看更多動畫指南和食譜,請前往 docs.flutter.dev:

參考文件