Introduction to Flame with Flutter

1. Introduction

What you'll build

Flame is a Flutter-based 2D game engine. In this codelab, you'll build a game inspired by one of the classics of '70s video games, Steve Wozniak's Breakout. Using Google Antigravity, you'll prompt the agent step-by-step to build Flame Components for the bat, ball, and bricks, animate the bat's movement with Flame Effects, and integrate Flame with Flutter's state management system.

When complete, your game should look like this animated gif, albeit a tad slower:

A screen recording of the completed brick breaker game being played, sped up significantly.

Your completed game meets the following requirements:

  • Functions on all six platforms that Flutter supports: Android, iOS, Linux, macOS, Windows, and the web.
  • Maintains at least 60 fps using Flame's game loop.
  • Uses Flutter packages like google_fonts and flutter_animate to recreate the feel of '70s and '80s arcade gaming.

Your learning journey

This codelab takes you through building the game step by step:

  1. Set up your Flutter environment - Configure Flutter and Google Antigravity for your target platform.
  2. Create a project - Prompt Antigravity to scaffold an empty Flutter project with Flame, flutter_animate, google_fonts, and material_ui.
  3. Create the game - Configure a fixed-resolution camera and add a PlayArea component to the game world.
  4. Display the ball - Add a moving Ball component driven by Flame's game loop and velocity vectors.
  5. Bounce around - Enable collision detection and hitboxes so the ball bounces off the walls.
  6. Get bat on ball - Add a player-controlled Bat supporting drag and keyboard input with MoveToEffect.
  7. Break down the wall - Generate a grid of Brick components and scale the ball's speed as bricks break.
  8. Win the game - Manage game states and display retro Flutter widget overlays with GameWidget.controlled.
  9. Keep score - Synchronize the player's score with Flutter UI using ValueNotifier and animate overlays with flutter_animate.

What you'll learn

  • How to collaborate with Google Antigravity to iteratively build and customize a Flame game.
  • How the basics of Flame work, starting with GameWidget.
  • How to use a game loop for frame-rate independent movement.
  • How Flame's Components work (akin to Flutter's Widgets).
  • How to detect and respond to collisions using hitboxes.
  • How to use Effects to animate and remove Components.
  • How to overlay Flutter Widgets on top of a Flame game.
  • How to integrate Flame with Flutter's state management.

Prerequisites

  • Basic familiarity with Flutter 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 game's components, review the key Flame concepts in the generated code, and optionally explore era-inspired arcade variations.

Choose a development target

Flutter produces apps for multiple platforms. Your app can run on any of the following operating systems:

  • iOS
  • Android
  • Windows
  • macOS
  • Linux
  • web

It's common practice to choose one operating system as your development target. This is the operating system that your app runs on during development.

A laptop labeled “development device” connected by a cable to a phone labeled “target device”.

For example, suppose you're using a Windows laptop to develop your Flutter app. If you choose Android as your development target, you attach an Android device to your Windows laptop with a USB cable, and your app-in-development runs on that attached Android device (or in an Android emulator). Alternatively, you can choose Windows as the development target, which runs your app-in-development as a desktop Windows app alongside your editor.

Make your choice before continuing. You can always run your app on other operating systems later. Choosing a development target makes the next step smoother.

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, 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 initial Flame game.

Troubleshooting

If you encounter setup issues, these Stack Overflow questions and answers might help:

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 game (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 dependencies, and wire up a minimal Flame game:
Create a new empty Flutter project named `brick_breaker` for a Breakout-style 2D arcade game. Add the `flame`, `flutter_animate`, `google_fonts`, and `material_ui` packages, and update `lib/main.dart` (importing `package:flame/game.dart` and `package:material_ui/material_ui.dart`) to run a basic `FlameGame` inside a `GameWidget`.

Understanding the generated code

Antigravity runs flutter create --empty to scaffold the project, adds flame, flutter_animate, google_fonts, and material_ui to pubspec.yaml, and updates lib/main.dart to host a FlameGame instance inside Flutter's GameWidget:

void main() {
  final game = FlameGame();
  runApp(GameWidget(game: game));
}

Run and test the game

Run the app on your chosen development target to verify everything is working. It displays a new window with a blank black background. The world's simplest video game is now rendering at 60 fps!

The brick_breaker application window with a completely black background.

4. Create the game

Size up the game

A game played in two dimensions (2D) needs a play area. In this step, you construct a play area of specific dimensions and use those dimensions to size the rest of the game's components.

There are various ways to lay out coordinates in a playing area. By one convention, you measure direction from the center of the screen with the origin (0,0) at the center, where positive values move items to the right along the x axis and up along the y axis. This standard is common in modern 3D game engines.

When the original Breakout game was created, the convention was to place the origin in the top-left corner. The positive x direction pointed right, and the positive y direction pointed down. To stay true to the era, this game sets the origin to the top-left corner.

Prompt Antigravity to create the game and PlayArea

Send the following prompt in Antigravity to set up the fixed-resolution game world and play area:

Create a `BrickBreaker` subclass of `FlameGame` in `lib/src/brick_breaker.dart` with a fixed-resolution camera (820x1600, defined in `lib/src/config.dart`) anchored at the top-left corner. Add a `PlayArea` rectangle component (`lib/src/components/play_area.dart`, re-exported in `lib/src/components/components.dart`) that fills the game's width and height with a warm arcade background color (`0xfff2e8cf`), and wire `BrickBreaker` up in `lib/main.dart`.

Understanding the generated code

PlayArea and Flame Components

Where Flutter has Widgets, Flame has Components. Where Flutter apps consist of trees of widgets, Flame games maintain trees of components.

Flutter's widget tree is an immutable description used to update the persistent and mutable RenderObject layer. Flame's components are persistent and mutable, designed to be used directly as part of a simulation system in lib/src/components/play_area.dart:

class PlayArea extends RectangleComponent with HasGameReference<BrickBreaker> {
  PlayArea() : super(paint: Paint()..color = const Color(0xfff2e8cf));

  @override
  FutureOr<void> onLoad() async {
    super.onLoad();
    size = Vector2(game.width, game.height);
  }
}

To control import clutter as you add more components, lib/src/components/components.dart uses the export directive to re-export every component from a single barrel file.

Fixed-resolution camera and the world

In lib/src/brick_breaker.dart, BrickBreaker configures the game to use a fixed 820x1600 resolution:

class BrickBreaker extends FlameGame {
  BrickBreaker()
    : super(
        camera: CameraComponent.withFixedResolution(
          width: gameWidth,
          height: gameHeight,
        ),
      );

  @override
  FutureOr<void> onLoad() async {
    super.onLoad();
    camera.viewfinder.anchor = Anchor.topLeft;
    world.add(PlayArea());
  }
}

The game resizes to fill the window that contains it and adds letterboxing as required.

In onLoad, the code performs two key actions:

  1. Configures the top-left corner as the anchor for the viewfinder (which defaults to the center of the area as (0,0)).
  2. Adds PlayArea to world, which projects all of its children through the CameraComponent's view transformation.

Run and test the game

Perform a hot restart (or full restart) to see the changes.

The brick_breaker application window with a sand-colored PlayArea rectangle centered in the window.

In the next step, you'll add a ball to the world and get it moving!

5. Display the ball

Prompt Antigravity to add the Ball component

Putting a moving ball on the screen involves defining a Ball component and adding it to the game world. Send the following prompt in Antigravity:

Add a `Ball` circle component (`lib/src/components/ball.dart`) with a radius of 2% of the game width and a velocity vector that updates the ball's position each frame (`position += velocity * dt`). Spawn the ball at the center of the play area in `BrickBreaker.onLoad()` moving downward in a randomized direction at a consistent speed (scaled to a quarter of the game height), and enable `debugMode = true` so we can see component bounds.

Understanding the generated code

Derived configuration constants

Defining ballRadius = gameWidth * 0.02 in lib/src/config.dart as a derived constant lets you modify the top-level gameWidth and gameHeight to explore how the game's look and feel changes as a result.

Frame-rate independent motion in Ball

CircleComponent, like RectangleComponent, derives from PositionComponent, so its position can be updated on every frame in lib/src/components/ball.dart:

  final Vector2 velocity;

  @override
  void update(double dt) {
    super.update(dt);
    position += velocity * dt;
  }

Velocity is a Vector2 object because velocity has both speed and direction. Flame calls update every frame, passing dt (the delta time in seconds since the previous frame). Multiplying velocity * dt keeps the simulation speed consistent across different display refresh rates (such as 60Hz versus 120Hz).

Normalizing the initial velocity

In lib/src/brick_breaker.dart, the ball starts at the center (size / 2) with a randomized downward velocity:

    world.add(
      Ball(
        radius: ballRadius,
        position: size / 2,
        velocity: Vector2(
          (rand.nextDouble() - 0.5) * width,
          height * 0.2,
        ).normalized()..scale(height / 4),
      ),
    );

Calling normalized() produces a unit vector (length 1) pointing in the same random direction, and ..scale(height / 4) scales it so the ball always starts at the same speed regardless of angle.

Run and test the game

Hot restart the game. With debugMode = true enabled, Flame displays purple bounding boxes and coordinates on the component tree:

The brick_breaker application window with a blue ball on top of the sand-colored play area, annotated with debug coordinates.

If you restart your game a few times, you'll notice the ball flies right through the edges of the play area. To fix that, you'll add collision detection in the next step.

6. Bounce around

Prompt Antigravity to add collision detection

Collision detection lets your game recognize when two components come into contact. Send the following prompt in Antigravity:

Enable collision detection on `BrickBreaker` and add hitboxes to `PlayArea` and `Ball`. In `Ball.onCollisionStart`, bounce the ball off the top, left, and right walls of `PlayArea` by reversing the appropriate velocity axis, and remove the ball when it hits the bottom edge.

Understanding the generated code

Hitboxes and HasCollisionDetection

Adding the HasCollisionDetection mixin to BrickBreaker tracks component hitboxes (RectangleHitbox on PlayArea and CircleHitbox on Ball) and triggers collision callbacks on every game tick.

Handling wall collisions in Ball

In lib/src/components/ball.dart, onCollisionStart reflects the ball's velocity vector when it hits the top, left, or right wall, and removes the ball when it hits the bottom:

  @override
  void onCollisionStart(
    Set<Vector2> intersectionPoints,
    PositionComponent other,
  ) {
    super.onCollisionStart(intersectionPoints, other);
    if (other is PlayArea) {
      if (intersectionPoints.first.y <= 0) {
        velocity.y = -velocity.y;
      } else if (intersectionPoints.first.x <= 0) {
        velocity.x = -velocity.x;
      } else if (intersectionPoints.first.x >= game.width) {
        velocity.x = -velocity.x;
      } else if (intersectionPoints.first.y >= game.height) {
        removeFromParent();
      }
    } else {
      debugPrint('collision with $other');
    }
  }

Run and test the game

Hot restart the game. Watch the ball bounce off the left and right walls of the PlayArea and disappear when it reaches the bottom edge.

Now that the ball bounces off the walls, give the player a bat to hit the ball back up!

7. Get bat on ball

Prompt Antigravity to add the Bat component

Send the following prompt in Antigravity to create the player-controlled Bat component and handle bat-on-ball collisions:

Add a player-controlled `Bat` component (`lib/src/components/bat.dart`) positioned near the bottom of the play area (`height * 0.95`). Render it as a rounded rectangle with a `RectangleHitbox`, and let the player move it horizontally both by dragging (`DragCallbacks`) and with the left and right arrow keys (`KeyboardEvents` on `BrickBreaker` using a short `MoveToEffect`). In `Ball`, replace immediate bottom removal with a delayed `RemoveEffect(delay: 0.35)`, and when the ball hits the `Bat`, reverse its vertical velocity and deflect its horizontal velocity based on how far from the bat's center the ball struck.

Understanding the generated code

Custom rendering, dragging, and MoveToEffect in Bat

Unlike PlayArea and Ball, Bat in lib/src/components/bat.dart extends PositionComponent directly and overrides render to draw a rounded rectangle (RRect):

  @override
  void render(Canvas canvas) {
    super.render(canvas);
    canvas.drawRRect(
      RRect.fromRectAndRadius(Offset.zero & size.toSize(), cornerRadius),
      _paint,
    );
  }

Offset.zero & size.toSize() uses the & operator on Offset and Size to construct a Rect.

For input, Bat supports two modalities:

  • Mouse and touch drag using DragCallbacks and onDragUpdate.
  • Keyboard movement using moveBy(double dx), which attaches a Flame MoveToEffect to smoothly animate the bat over 100ms:
  void moveBy(double dx) {
    add(
      MoveToEffect(
        Vector2((position.x + dx).clamp(0, game.width), position.y),
        EffectController(duration: 0.1),
      ),
    );
  }

Delayed removal and angled bat bounce in Ball

In lib/src/components/ball.dart, two improvements make the ball interaction feel much better:

  1. Replacing removeFromParent() with add(RemoveEffect(delay: 0.35)) lets the ball travel past the bottom edge before disappearing.
  2. When colliding with Bat, velocity.x is adjusted based on where the ball struck the bat relative to the bat's center:
    } else if (other is Bat) {
      velocity.y = -velocity.y;
      velocity.x =
          velocity.x +
          (position.x - other.position.x) / other.size.x * game.width * 0.3;
    }

Run and test the game

Hot restart the game. Move the bat by dragging it with your mouse or finger, or by pressing the Left and Right arrow keys, and bounce the ball back toward the top of the screen.

Now that you have a bat to hit the ball, add a wall of bricks to break!

8. Break down the wall

Prompt Antigravity to add the Bricks

Send the following prompt in Antigravity to create the Brick component, lay out the brick grid, and speed up the ball as bricks break:

Create a `Brick` rectangle component (`lib/src/components/brick.dart`) with a hitbox and add a 10-column by 5-row grid of colored bricks across the top of the play area using constants in `lib/src/config.dart`. When the ball collides with a brick, remove the brick, reflect the ball's velocity off the side of the brick it hit, and multiply the ball's velocity by a `difficultyModifier` (such as `1.03`) so the game speeds up. When the last brick is destroyed, remove the ball and bat from the world.

Understanding the generated code

Queued component removal and the win check

In lib/src/components/brick.dart, Brick.onCollisionStart removes the brick and checks whether it was the final brick in the world:

  @override
  void onCollisionStart(
    Set<Vector2> intersectionPoints,
    PositionComponent other,
  ) {
    super.onCollisionStart(intersectionPoints, other);
    removeFromParent();

    if (game.world.children.query<Brick>().length == 1) {
      game.world.removeAll(game.world.children.query<Ball>());
      game.world.removeAll(game.world.children.query<Bat>());
    }
  }

Why does the check compare query().length == 1 after calling removeFromParent()? Because component removal in Flame is a queued command—the brick is only removed from the component tree after the current callback finishes, before the next game tick.

Difficulty curve in Ball

When Ball collides with a Brick in lib/src/components/ball.dart, it reflects the appropriate velocity axis and multiplies the velocity vector by difficultyModifier (1.03), gradually increasing the ball's speed with every brick broken:

    } else if (other is Brick) {
      if (position.y < other.position.y - other.size.y / 2) {
        velocity.y = -velocity.y;
      } else if (position.y > other.position.y + other.size.y / 2) {
        velocity.y = -velocity.y;
      } else if (position.x < other.position.x) {
        velocity.x = -velocity.x;
      } else if (position.x > other.position.x) {
        velocity.x = -velocity.x;
      }
      velocity.setFrom(velocity * difficultyModifier);
    }

Run and test the game

Hot restart the game to see the full brick wall in action:

The brick_breaker game with the ball, bat, and colored bricks on the playing area with debug labels.

Next, you'll add welcome, game over, and win overlays using Flutter widgets!

9. Win the game

Prompt Antigravity to add PlayState and Flutter overlays

In this step, you introduce a PlayState enum, embed the Flame game inside a styled Flutter GameApp widget with overlays, and configure platform network permissions for google_fonts. Send the following prompt in Antigravity:

Add a `PlayState` enum (`welcome`, `playing`, `gameOver`, `won`) to `BrickBreaker` that synchronizes with Flame's `overlays`, turn off `debugMode`, and move spawning the ball, bat, and bricks into a `startGame()` method triggered by tapping the screen (`TapCallbacks`) or pressing Space or Enter. Transition to `gameOver` when the ball exits the bottom and `won` when the final brick breaks. Then create a Flutter wrapper `GameApp` (`lib/src/widgets/game_app.dart`, importing `package:material_ui/material_ui.dart`) using the `'Press Start 2P'` Google Font and a gradient background that displays `GameWidget` overlays for `'TAP TO PLAY'`, `'G A M E   O V E R'`, and `'Y O U   W O N ! ! !'`. Also add the required Android and macOS network permissions for `google_fonts`.

Understanding the generated code

Managing overlays with PlayState

In lib/src/brick_breaker.dart, the playState setter synchronizes the game's state with Flame's overlays manager:

  late PlayState _playState;
  PlayState get playState => _playState;
  set playState(PlayState playState) {
    _playState = playState;
    switch (playState) {
      case PlayState.welcome:
      case PlayState.gameOver:
      case PlayState.won:
        overlays.add(playState.name);
      case PlayState.playing:
        overlays.remove(PlayState.welcome.name);
        overlays.remove(PlayState.gameOver.name);
        overlays.remove(PlayState.won.name);
    }
  }

Splitting startGame() out of onLoad() lets the player start or restart a game at any time by tapping the screen (onTapDown) or pressing Space or Enter.

Mapping overlays in GameWidget

In lib/src/widgets/game_app.dart, GameWidget.controlled constructs the BrickBreaker instance and maps each PlayState name to a Flutter widget overlay:

child: GameWidget.controlled(
  gameFactory: BrickBreaker.new,
  overlayBuilderMap: {
    PlayState.welcome.name: (context, game) => Center(
      child: Text(
        'TAP TO PLAY',
        style: Theme.of(context).textTheme.headlineLarge,
      ),
    ),
    // ...
  },
),

Each key in overlayBuilderMap must match the overlay name passed to overlays.add(...) and overlays.remove(...).

Run and test the game

Stop and re-run the app (since platform network permissions were updated for google_fonts). Verify that 'TAP TO PLAY' appears on launch, tapping or pressing Space starts the game, and losing the ball displays 'G A M E O V E R'.

10. Keep score

Prompt Antigravity to add the score card and animated overlays

In this final step, you expose the player's score from Flame to Flutter using a ValueNotifier and polish the overlays with flutter_animate. Send the following prompt in Antigravity:

Track the player's score in `BrickBreaker` using a `ValueNotifier<int> score` that resets in `startGame()` and increments whenever a brick is broken. Using `package:material_ui/material_ui.dart`, create a `ScoreCard` widget (`lib/src/widgets/score_card.dart`) above the `GameWidget` that listens to `score`, and an `OverlayScreen` widget (`lib/src/widgets/overlay_screen.dart`) using `flutter_animate` to slide in the overlay title and pulse the subtitle in and out.

Understanding the generated code

Bridging Flame state to Flutter with ValueNotifier

In lib/src/brick_breaker.dart, BrickBreaker exposes final ValueNotifier score = ValueNotifier(0);, which resets in startGame() and increments each time a Brick is hit.

In lib/src/widgets/score_card.dart, ScoreCard uses ValueListenableBuilder so only the score text rebuilds when score.value changes:

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<int>(
      valueListenable: score,
      builder: (context, score, child) {
        return Padding(
          padding: const EdgeInsets.fromLTRB(12, 6, 12, 18),
          child: Text(
            'Score: $score'.toUpperCase(),
            style: Theme.of(context).textTheme.titleLarge!,
          ),
        );
      },
    );
  }

Animating overlays with flutter_animate

In lib/src/widgets/overlay_screen.dart, OverlayScreen chains flutter_animate effects onto standard Text widgets to slide the title in and pulse the subtitle:

Text(
  title,
  style: Theme.of(context).textTheme.headlineLarge,
).animate().slideY(duration: 750.ms, begin: -3, end: 0),
const SizedBox(height: 16),
Text(subtitle, style: Theme.of(context).textTheme.headlineSmall)
    .animate(onPlay: (controller) => controller.repeat())
    .fadeIn(duration: 1.seconds)
    .then()
    .fadeOut(duration: 1.seconds),

To get a more in-depth look at the power of flutter_animate and Flutter animations, check out the flutter_animate package documentation and the Animations in Flutter codelab.

Run and test the game

Hot restart the game. With everything in place, you can now play your brick breaker game on any of the six Flutter target platforms:

The brick_breaker game showing the welcome overlay inviting the user to tap the screen to play

The brick_breaker game showing the game over overlay on top of the bat and remaining bricks

11. Congratulations

Congratulations! You built a complete 2D arcade game with Flutter, Flame, and Google Antigravity.

What you've built

  • A fixed-resolution 2D Flame game world (BrickBreaker and PlayArea) that scales and letterboxes cleanly across mobile, desktop, and web.
  • Physics and collision components (Ball, Bat, and Brick) using HasCollisionDetection, hitboxes, and frame-rate independent velocity updates.
  • Multi-modal player controls and Flame effects combining touch and mouse dragging (DragCallbacks) with keyboard-driven MoveToEffect animations and delayed RemoveEffect cleanup.
  • Flutter UI integration using GameWidget.controlled overlays, ValueNotifier state management for real-time score updates, google_fonts, and flutter_animate.

Where to go from here

Continue prompting Antigravity to make the game your own! Here are a few ideas to try:

  • Retro arcade sound effects: Prompt Antigravity to add flame_audio (or synthesized audio effects) for paddle hits, wall bounces, and brick destruction.
  • Power-ups and multi-ball: Spawn falling power-up capsules from broken bricks that widen the bat, slow the ball, or split the ball into three.
  • Multiple levels and high scores: Persist the player's high score using shared_preferences and design new brick layouts for subsequent levels.

What's next?

Check out some of these related codelabs:

Further reading