Animations in Flutter

1. Introduction

Animations are a great way to improve the user experience of your app, communicate important information to the user, and make your app more polished and enjoyable to use.

What you'll build

In this codelab, you'll collaborate with Google Antigravity to build a multiple-choice quiz game that features a variety of Flutter animation effects and techniques.

Animated recording of the completed Flutter Quiz app showing animated scoreboard stars, sliding question cards, 3D flipping answer cards, and container transitions.

Using Antigravity, you'll iteratively prompt the agent to:

  • Build a scoreboard widget that animates its size and color using implicit animations, tweens, and easing curves.
  • Animate question transitions with explicit SlideTransition and FadeTransition effects inside an AnimatedSwitcher.
  • Build a custom 3D card flip effect driven by an AnimationController and staggered with a TweenSequence.
  • Use prebuilt Material motion transitions (FadeThroughTransition and OpenContainer) from the animations package and add Android's predictive back gesture support.

Overview of Flutter's animation framework

Flutter displays animation effects by rebuilding a portion of the widget tree on each frame. It provides prebuilt animation effects and composable APIs to make creating and coordinating animations straightforward:

  • Implicit animations are prebuilt animation effects that run the entire animation automatically. When the target value of the animation changes, the widget animates smoothly from the current value to the target value, displaying each value in between. Examples include AnimatedSize, AnimatedScale, and AnimatedPositioned.
  • Explicit animations are prebuilt animation effects that take an Animation object to drive their progress. Examples include SizeTransition, ScaleTransition, SlideTransition, and FadeTransition.
  • Animation is a class that represents a running or stopped animation. It exposes a current value and status, extends Listenable, and notifies its listeners as the animation progresses.
  • AnimationController creates an Animation and controls its lifecycle. Methods such as forward(), reset(), stop(), and repeat() control playback independently of the visual effect being rendered.
  • Tweens interpolate values between a begin and end value and can represent any type, such as double, Offset, or Color.
  • Curves adjust the rate of change of a parameter over time. Applying an easing curve makes an animation accelerate or decelerate naturally. Curves map an input value between 0.0 and 1.0 to an output value.

Your learning journey

This codelab takes you through building and animating the quiz app step by step:

  1. Set up your Flutter environment - Configure the Flutter SDK and Google Antigravity for your target platform.
  2. Create a project - Prompt Antigravity to scaffold a multiple-choice quiz app structured with the Model-View-ViewModel (MVVM) pattern.
  3. Use implicit animation effects - Add a star-based Scoreboard that animates scale and color with AnimatedScale, TweenAnimationBuilder, and Curves.elasticOut.
  4. Use explicit animation effects - Animate incoming and outgoing questions using AnimatedSwitcher, SlideTransition, FadeTransition, and a custom layoutBuilder.
  5. Control the state of an animation - Build a custom 3D CardFlipEffect using AnimationController, AnimatedBuilder, Transform, and a staggered TweenSequence.
  6. Use custom navigation transitions - Add PageTransitionsTheme with PredictiveBackPageTransitionsBuilder, switch questions with PageTransitionSwitcher and FadeThroughTransition, and expand into a game over screen with OpenContainer.

What you'll learn

  • How to collaborate with Google Antigravity to iteratively build and customize a Flutter app with rich animations.
  • How to use implicitly animated widgets (AnimatedScale and TweenAnimationBuilder) to achieve polished animations with minimal code.
  • How to compose explicitly animated widgets (SlideTransition and FadeTransition) driven by an Animation object.
  • How to use AnimationController and TweenSequence to build a staggered 3D widget transition.
  • How to use the animations package and PredictiveBackPageTransitionsBuilder to deliver Material motion and Android predictive back transitions.

Prerequisites

  • Basic familiarity with Flutter widgets and Dart syntax.

2. Set up your Flutter environment

Editor

This codelab uses Google Antigravity as your AI-first development environment. In each step, you prompt Antigravity to generate or evolve your app's components, review the key Flutter animation concepts in the generated code, and optionally explore creative variations.

Choose a development target

You can run this codelab on any of the following target platforms:

  • An Android physical device or emulator (recommended for testing predictive back gestures in the navigation transitions step).
  • An iOS physical device or the iOS Simulator (requires Xcode on macOS).
  • A web browser (such as Chrome).
  • A Windows, macOS, or Linux desktop target.

Install Flutter

The most up-to-date instructions on installing the Flutter SDK are always on docs.flutter.dev.

The instructions on the Flutter website cover installing the SDK, platform-specific tools, and editor plugins. For this codelab, install the following software:

  1. Flutter SDK
  2. Google Antigravity with the official Dart and Flutter plugin enabled (available in the Plugin Marketplace under the Build with Google section).
  3. Compiler software for your chosen development target (for example, Android Studio to target Android, Visual Studio to target Windows, or Xcode to target macOS or iOS).

In the next step, you'll prompt Antigravity to create your Flutter project and scaffold the quiz starter app.

3. Create a project

Prompt Antigravity to create the project

  1. Launch Google Antigravity and open an empty directory where you'd like to build your project (choose a path that doesn't require elevated privileges or contain spaces, such as a folder in your home directory or C:\src\).
  2. In the Antigravity agent chat panel, send the following prompt to create the Flutter project, add the animations and material_ui dependencies, and scaffold the MVVM quiz app:
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`.

Understanding the generated code

Antigravity scaffolds a multiple-choice quiz game consisting of two screens structured with the Model-View-ViewModel (MVVM) pattern:

  • lib/main.dart - Configures MaterialApp with Material 3 theming (package:material_ui/material_ui.dart) and launches HomeScreen.
  • lib/home_screen.dart - Displays the title screen with a New Game button that navigates to QuestionScreen.
  • lib/model.dart - Defines the Question data class and QuestionBank, which draws random questions until the bank is empty.
  • lib/view_model.dart - Defines QuizViewModel, a ChangeNotifier that tracks the current question, player score, and game-over state.
  • lib/question_screen.dart - Renders QuestionScreen (the View), which listens to QuizViewModel and composes QuestionCard, AnswerCards, and StatusBar.

Reactive state with QuizViewModel and ListenableBuilder

In lib/view_model.dart, QuizViewModel extends ChangeNotifier and calls notifyListeners() whenever the user selects an answer or advances to the next question:

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;
  // ...

In lib/question_screen.dart, QuestionScreen wraps its Scaffold in a ListenableBuilder so the UI rebuilds automatically whenever viewModel notifies its listeners:

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

Run and test the app

Run the app on your chosen target device to verify the starter project works as expected.

Starter Flutter Quiz app showing the HomeScreen and QuestionScreen side by side

Tap New Game and answer a few questions. Right now, the app updates the score text, question card, and answer cards immediately without any animation effects (aside from Navigator's default route transition). In the next step, you'll add implicit animations to the scoreboard.

4. Use implicit animation effects

Implicit animations are often the fastest way to add motion to a Flutter app because they manage their own internal animation state automatically. Whenever a target property (such as scale, opacity, or padding) changes, an ImplicitlyAnimatedWidget interpolates smoothly from the old value to the new value over the specified duration.

In this step, you'll replace the plain-text status bar with a star-based Scoreboard that animates both the scale and color of each star when the player scores a point.

Animated GIF showing the scoreboard stars bouncing and changing color from grey to yellow

Prompt Antigravity to add an animated star scoreboard

Send the following prompt in Antigravity to create lib/scoreboard.dart and integrate it into 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.

Understanding the generated code

Implicit scaling with AnimatedScale

In lib/scoreboard.dart, Scoreboard displays one AnimatedStar for each question in the quiz, passing isActive: score > i. Inside AnimatedStar, AnimatedScale scales its child from 0.5 to 1.0 whenever isActive becomes true:

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

If you only used AnimatedScale with a static Icon color, the star's size would animate smoothly while its color would snap instantly from grey to yellow:

Animated GIF showing the star scaling smoothly while its color changes immediately

Interpolating colors with TweenAnimationBuilder and ColorTween

To animate the star's color alongside its scale, you might consider AnimatedContainer (which animates container decorations) or AnimatedIcon (which morphs between predefined icon pairs in AnimatedIcons). However, neither animates the color of a standard Icons.star widget.

Instead, the generated code uses TweenAnimationBuilder, a versatile ImplicitlyAnimatedWidget that animates any property using a Tween. A Tween takes begin and end values and calculates the intermediate values across the animation's timeline. Here, ColorTween interpolates between the inactive grey and active yellow colors:

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);
  },
),

Whenever Tween.end changes based on isActive, TweenAnimationBuilder automatically animates from its current value to the new end value—even if isActive changes while an animation is already in flight:

Animated GIF showing the star smoothly animating both scale and color

Applying an easing curve with Curves.elasticOut

Animations that run at a constant linear rate can feel mechanical. A Curve applies an easing function that varies the rate of change over time, mapping an input progress value between 0.0 and 1.0 (on the x-axis) to an output value (on the y-axis). Flutter includes a rich catalog of prebuilt curves in the Curves class, such as Curves.easeIn and Curves.easeOut:

Graph of the Curves.easeIn easing function showing slow initial progress that accelerates toward 1.0.Graph of the Curves.easeOut easing function showing fast initial progress that decelerates toward 1.0.

Passing Curves.elasticOut to both AnimatedScale and TweenAnimationBuilder produces an energetic spring effect that overshoots and settles at the end:

Graph of the Curves.elasticOut easing function showing an oscillating spring curve settling at 1.0.

Run and test the app

Hot reload the app and answer a question correctly to watch the star bounce and glow gold in StatusBar.

Use DevTools to inspect slow animations

To inspect fast animations frame by frame, Flutter DevTools provides a Slow animations toggle that slows down all animations in your app by 5x. Open the Flutter Inspector in DevTools while running in debug mode and click the Slow animations button in the toolbar:

Flutter DevTools Widget Inspector toolbar highlighting the Slow animations button

5. Use explicit animation effects

Like implicit animations, explicit animations are prebuilt animation widgets, but instead of taking a target value, they take an Animation object as a parameter. This makes them ideal when an Animation is provided by a parent widget—such as AnimatedSwitcher, a route transition, or your own AnimationController—and when you want to compose multiple transitions together.

In this step, you'll animate QuestionCard so that new questions slide and fade in smoothly without jumping in layout.

Prompt Antigravity to animate question transitions

Send the following prompt in Antigravity to update QuestionCard in lib/question_screen.dart:

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.

Understanding the generated code

Composing SlideTransition and FadeTransition in AnimatedSwitcher

AnimatedSwitcher automatically runs a transition whenever its child changes to a widget with a different Key.

By default, AnimatedSwitcher cross-fades between the old and new children, but its transitionBuilder callback gives you the incoming and outgoing child widgets and an Animation so you can build custom explicit animations.

In lib/question_screen.dart, the generated transitionBuilder uses SlideTransition (which requires an Animation) wrapped in a 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),
  );
},

Every Tween provides an animate() method that transforms an input Animation into a new Animation with that tween applied. You can also chain tweens concisely using Animation.drive():

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

Preventing layout jumps with layoutBuilder

Without a custom layoutBuilder, AnimatedSwitcher centers its children in a Stack while the transition is running, and then snaps the card back to the top of the available space once the animation finishes:

Animated GIF showing QuestionCard jumping from the center of the Stack to the top when the transition finishes

Overriding layoutBuilder to use Alignment.topCenter (instead of the Alignment.center used by AnimatedSwitcher.defaultLayoutBuilder) keeps the incoming and outgoing cards aligned at the top throughout the transition:

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

Run and test the app

Hot reload the app, answer a question, and tap Next to verify that the new QuestionCard slides and fades in smoothly at the top of the screen.

Key concepts learned

  • Explicit animation widgets take an Animation object rather than a single target value and duration.
  • The Animation class represents animation progress over time without being tied to a specific visual property.
  • Tween.animate() and Animation.drive() transform and apply CurveTweens to an Animation.
  • AnimatedSwitcher.layoutBuilder customizes how incoming and outgoing children are aligned during a transition.

6. Control the state of an animation

So far, Flutter has managed the playback of every animation for you. When you need complete control over when an animation starts, stops, resets, or sequences multiple phases, you can create your own Animation using an AnimationController.

In this step, you'll build a custom CardFlipEffect widget that flips each answer card in 3D when the question changes, using a TweenSequence to stagger the four cards so they flip one after another.

Prompt Antigravity to build a staggered 3D card flip effect

Send the following prompt in Antigravity to create lib/flip_effect.dart and wrap the answer cards in 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`.

Understanding the generated code

Managing animation lifecycle with AnimationController

Creating a custom animation with AnimationController follows four steps:

  1. Create a StatefulWidget (CardFlipEffect).
  2. Mix SingleTickerProviderStateMixin into the State class so it can provide a frame Ticker.
  3. Initialize the AnimationController in initState() with vsync: this, and trigger forward() in didUpdateWidget() whenever widget.child.key changes.
  4. Rebuild the widget tree on each tick using AnimatedBuilder.

3D rotation with AnimatedBuilder and Transform

For 2D rotation, Flutter provides AnimatedRotation (implicit) and RotationTransition (explicit). Because a 3D X-axis card flip requires a Matrix4 transformation and swapping the front and back widgets midway through the flip (value < 0.5), CardFlipEffect combines AnimatedBuilder with 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,
  );
}

During the first half of the rotation (_animationWithDelay.value < 0.5), the widget displays _previousChild. Once the card rotates past 90 degrees, it displays the new child flipped vertically (Transform.flip(flipY: true)) so the text appears right-side up as the rotation completes at $\pi$ radians:

Animated GIF showing the answer cards flipping over in 3D when advancing to the next question.

Staggering animations with TweenSequence

Notice that CardFlipEffect does not use Future.delayed from dart:async to stagger the cards. Keeping the delay inside the animation timeline using TweenSequence means the entire staggered effect is driven by the same TickerProvider—so enabling Slow animations in Flutter DevTools slows down the delay proportionally as well.

In lib/flip_effect.dart, _animationWithDelay chains two TweenSequenceItems: a ConstantTween(0.0) weighted by delayAmount followed by a Tween(begin: 0.0, end: 1.0) weighted by 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);

In AnswerCards (lib/question_screen.dart), passing delayAmount: index.toDouble() / 2 gives each card in the grid a progressively longer initial hold before flipping:

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

Run and test the app

Perform a hot restart, answer a question, and tap Next to watch the four answer cards flip over one by one.

Animated GIF showing the four answer cards flipping one by one with a staggered delay

7. Use custom navigation transitions

In addition to animating widgets within a single screen, you can animate transitions between screens and major UI states. In this step, you'll use prebuilt Material motion widgets from the official animations package on pub.dev (FadeThroughPageTransitionsBuilder, PageTransitionSwitcher, FadeThroughTransition, and OpenContainer) and enable Android's predictive back gesture.

Prompt Antigravity to add Material motion and predictive back transitions

Send the following prompt in Antigravity to update lib/main.dart and 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.

Understanding the generated code

Custom route transitions and Android predictive back

When you want to customize a single navigation call, you can pass a PageRouteBuilder to Navigator.push() and supply a transitionsBuilder (such as FadeTransition or FadeThroughTransition) that receives both the primary animation and secondaryAnimation.

To apply consistent route transitions across your entire app—and support Android's predictive back gesture—configure pageTransitionsTheme in your app's ThemeData (lib/main.dart):

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

Animated GIF on Android showing the user dragging back from the edge of the screen to peek at the HomeScreen behind the QuestionScreen.

Predictive back allows Android users to swipe from the edge of the screen and peek at the previous route before committing to navigating back. PredictiveBackPageTransitionsBuilder listens for system predictive back gestures on Android 14 (API 34) and higher, and gracefully falls back to ZoomPageTransitionsBuilder on earlier Android versions. See the Android predictive back guide for platform configuration details.

Switching questions with PageTransitionSwitcher and FadeThroughTransition

Standard AnimatedSwitcher only exposes a single Animation in its transitionBuilder. Because Material motion transitions like FadeThroughTransition coordinate both an incoming animation and an outgoing secondaryAnimation, QuestionCard uses PageTransitionSwitcher from the animations package:

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

Container transform with OpenContainer

OpenContainer expanding a closed card widget into a full-screen open widget

The OpenContainer widget implements Material's container transform pattern, smoothly expanding a smaller widget (closedBuilder) into a full-screen destination (openBuilder).

In lib/question_screen.dart, QuestionCard renders an OpenContainer with tappable: false so tapping the question card itself doesn't end the game. Instead, closedBuilder passes the openContainer callback up to _QuestionScreenState, which invokes it when the final question is answered:

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);
  },
),

Run and test the app

Hot restart the app, start a new game, and play through all three questions. When you answer the last question, OpenContainer smoothly expands the question card into the full-screen GameOverScreen:

Animated GIF showing the QuestionCard expanding using OpenContainer into the full-screen GameOverScreen.

8. Congratulations

Congratulations! You've collaborated with Google Antigravity to add rich animation effects to a Flutter quiz app and explored the core building blocks of Flutter's animation system.

What you've built

  • Implicitly animated scoreboard: Used AnimatedScale and TweenAnimationBuilder with ColorTween and Curves.elasticOut to animate star icons when the player scores.
  • Explicit question transitions: Composed FadeTransition and SlideTransition inside AnimatedSwitcher with a top-aligned layoutBuilder.
  • Staggered 3D card flips: Controlled a 3D Matrix4 rotation using AnimationController, AnimatedBuilder, and a TweenSequence delay.
  • Material motion & predictive back: Configured PageTransitionsTheme with PredictiveBackPageTransitionsBuilder and FadeThroughPageTransitionsBuilder, and used PageTransitionSwitcher and OpenContainer from the animations package.

Animated recording of the completed Flutter Quiz app with all animation effects enabled.

What's next?

Check out these related codelabs:

Further reading

Explore more animation guides and recipes on docs.flutter.dev:

Reference docs