Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 73 ยท Projects

Project: A Simple 2D Game

Build a small Flutter game: a Ticker game loop with delta time, a CustomPainter, drag input, rectangle collision and a score, with a canvas stand-in you can play.

Games are a great way to understand how Flutter draws. A game needs three things your usual forms and lists do not: a loop that runs every frame, direct drawing, and state that changes dozens of times per second. Flutter gives you all three without extra packages: a Ticker, a CustomPainter and a Listenable.

In this project you build "Catcher": coins fall from the top, you slide a basket left and right to catch them, each catch scores a point, and a miss costs a life. You will see the real Dart structure and then play a browser stand-in that uses the same loop, the same math and the same collision test.

Real vs stand-in. The Dart is real Flutter and read-only (the site cannot run it). The stand-ins are JavaScript: requestAnimationFrame plays the role of the Ticker, and the 2D canvas plays the role of Canvas. The game rules are identical, so the logic transfers directly. For the drawing API itself, see CustomPaint and Canvas.

The loop, every frame

Tick The engine tells you the elapsed time.
Update Move things by speed times dt.
Paint Draw the world from its state.
1 / 2

Design before code

Split the game into state, rules and drawing:

  • State: the basket's x position, a list of coins (x, y, size), the score, lives and a game-over flag.
  • Rules: a function update(dt) that moves coins down, spawns new ones on a timer, tests collisions and updates score and lives.
  • Drawing: a CustomPainter that only reads the state and paints it.

Keeping update free of any Flutter types makes it easy to test. That is the same separation you use in app architecture (choosing state management).

The game state

DART
class Coin {
  Coin(this.x, this.y);
  double x;
  double y;
  static const double size = 24;

  Rect get rect => Rect.fromLTWH(x, y, size, size);
}

class CatcherGame extends ChangeNotifier {
  CatcherGame({int seed = 7}) : _random = math.Random(seed);

  final math.Random _random;
  final List<Coin> coins = [];
  double basketX = 0;
  int score = 0;
  int lives = 3;
  double _spawnTimer = 0;
  Size world = Size.zero;

  static const double basketWidth = 80;
  static const double basketHeight = 16;
  static const double fallSpeed = 180; // pixels per second

  bool get isOver => lives <= 0;

  Rect get basketRect => Rect.fromLTWH(
        basketX, world.height - 40, basketWidth, basketHeight);

  void moveBasket(double dx) {
    basketX = (basketX + dx).clamp(0.0, world.width - basketWidth).toDouble();
  }

  void update(double dt) {
    if (isOver || world.isEmpty) return;

    _spawnTimer += dt;
    if (_spawnTimer >= 0.9) {
      _spawnTimer = 0;
      coins.add(Coin(_random.nextDouble() * (world.width - Coin.size), -Coin.size));
    }

    for (final coin in coins) {
      coin.y += fallSpeed * dt;
    }

    final basket = basketRect;
    coins.removeWhere((coin) {
      if (coin.rect.overlaps(basket)) {
        score++;
        return true;
      }
      if (coin.y > world.height) {
        lives--;
        return true;
      }
      return false;
    });

    notifyListeners();
  }
}

Three details deserve attention.

  1. Rect.overlaps is the classic axis-aligned bounding box (AABB) test: two rectangles overlap unless one is entirely left of, right of, above or below the other.
  2. removeWhere with side effects is compact, but the callback runs once per coin, so each coin scores or costs a life exactly once.
  3. A fixed seed gives the same coin sequence every run, which makes bugs reproducible and tests deterministic.

Try the rules without any drawing

Because update only touches numbers, you can run it in a console. This stand-in uses a small seeded random generator and prints a few seconds of the game.

JS Stand-in: the update rules, no graphics

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With the basket parked in the middle, you see lives drop whenever a coin lands elsewhere and the score rise when one happens to fall into the basket. Change basket.x and run again to see the numbers react.

The loop: Ticker

A Ticker calls a function once per frame, and gives you the total time elapsed since it started. You get one by mixing SingleTickerProviderStateMixin into a State:

DART
class GamePage extends StatefulWidget {
  const GamePage({super.key});
  @override
  State<GamePage> createState() => _GamePageState();
}

class _GamePageState extends State<GamePage>
    with SingleTickerProviderStateMixin {
  final game = CatcherGame();
  late final Ticker _ticker;
  Duration _last = Duration.zero;

  @override
  void initState() {
    super.initState();
    _ticker = createTicker((elapsed) {
      final dt = (elapsed - _last).inMicroseconds / 1e6;
      _last = elapsed;
      game.update(dt.clamp(0.0, 0.05).toDouble());
    })..start();
  }

  @override
  void dispose() {
    _ticker.dispose();
    game.dispose();
    super.dispose();
  }
  // build() below
}

The important lines:

  • dt is the time since the previous frame in seconds. Multiply every speed by it and the game runs at the same pace at 60 Hz, 120 Hz, or when a frame is slow.
  • clamp(0, 0.05) caps a long pause (the app was in the background, or a frame hitched) so coins do not teleport through the basket in one huge step.
  • The ticker is disposed with the state. A ticker left running throws an error when the state is destroyed. See explicit animations for how an AnimationController wraps the same idea.

Drawing with a repaint listenable

The key performance trick: do not call setState every frame. Instead, pass the game itself (a Listenable) to the painter's repaint argument. Flutter then repaints just that canvas on every notifyListeners(), without rebuilding any widgets.

DART
class GamePainter extends CustomPainter {
  GamePainter(this.game) : super(repaint: game);
  final CatcherGame game;

  @override
  void paint(Canvas canvas, Size size) {
    game.world = size;
    canvas.drawRect(Offset.zero & size, Paint()..color = const Color(0xFF1B1F3B));

    final coinPaint = Paint()..color = const Color(0xFFFFC107);
    for (final c in game.coins) {
      canvas.drawCircle(c.rect.center, Coin.size / 2, coinPaint);
    }

    canvas.drawRRect(
      RRect.fromRectAndRadius(game.basketRect, const Radius.circular(6)),
      Paint()..color = const Color(0xFF4DD0E1),
    );
  }

  @override
  bool shouldRepaint(GamePainter old) => old.game != game;
}

Assigning game.world inside paint is a shortcut that works for a small project. A cleaner version uses a LayoutBuilder to set the world size before the first frame, because paint should normally have no side effects.

Input

A horizontal drag moves the basket. Wrap the canvas in a GestureDetector and forward the delta:

DART
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: GestureDetector(
      onHorizontalDragUpdate: (d) => game.moveBasket(d.delta.dx),
      child: Stack(
        children: [
          Positioned.fill(child: CustomPaint(painter: GamePainter(game))),
          Positioned(
            top: 48, left: 16,
            child: ListenableBuilder(
              listenable: game,
              builder: (context, _) => Text(
                'Score ${game.score}   Lives ${game.lives}',
                style: const TextStyle(color: Colors.white, fontSize: 20),
              ),
            ),
          ),
        ],
      ),
    ),
  );
}

The score text lives in its own ListenableBuilder, so only that small widget rebuilds each tick, while the painter repaints on its own. For gesture details, read gestures and input. On desktop and web you would also add a Focus widget and arrow keys.

Play the stand-in

This is the full game on a browser canvas. Move the mouse or drag a finger over it to steer. It uses delta time, the same AABB test and the same spawn timer as the Dart version.

Stand-in: playable Catcher game

Ideas to extend it

  • Difficulty: reduce the spawn interval as the score grows.
  • Game over screen: show a button that creates a fresh CatcherGame.
  • Sprites: replace circles with images and use canvas.drawImageRect.
  • Pause: stop the ticker with _ticker.muted = true when the app is paused.
  • Tests: because update is plain Dart, a unit test with a fixed seed can assert the exact score after N simulated frames (see unit and widget testing).

For bigger games, the Flame engine adds components, collision helpers and sprite animation on top of exactly this loop.

Going further: Flame and 3D models

Flame

Everything above (the ticker, delta time, painting, collisions) is what the Flame engine packages for you. You write components; Flame runs the loop. A game is a FlameGame, and every moving thing is a Component in a tree, just like widgets but updated every frame.

DART
class CatcherGame extends FlameGame with HasCollisionDetection, PanDetector {
  late final Basket basket;

  @override
  Future<void> onLoad() async {
    basket = Basket()..position = Vector2(size.x / 2, size.y - 60);
    await add(basket);
    add(TimerComponent(period: 0.8, repeat: true, onTick: () => add(Coin(x: Random().nextDouble() * size.x))));
  }

  @override
  void onPanUpdate(DragUpdateInfo info) {
    basket.x = (basket.x + info.delta.global.x).clamp(0, size.x);
  }
}

class Coin extends PositionComponent with HasGameReference<CatcherGame>, CollisionCallbacks {
  Coin({required double x}) : super(position: Vector2(x, 0), size: Vector2.all(24));

  @override
  Future<void> onLoad() async => add(CircleHitbox());

  @override
  void update(double dt) {
    y += 220 * dt;                                      // pixels per second times seconds
    if (y > game.size.y) removeFromParent();            // missed
  }

  @override
  void onCollisionStart(Set<Vector2> points, PositionComponent other) {
    if (other is Basket) {
      removeFromParent();                               // caught: add to the score here
    }
  }

  @override
  void render(Canvas canvas) => canvas.drawCircle(const Offset(12, 12), 12, Paint()..color = Colors.amber);
}

// In a widget tree:
// GameWidget(game: CatcherGame())

You still see delta time (dt) and a canvas, but the engine adds the component tree, hitboxes and collision callbacks (HasCollisionDetection), input mixins, sprites and sprite sheets, audio and camera helpers. Use plain Flutter for casual, UI-heavy games (puzzles, cards, quizzes) and Flame once you have many moving objects, animation sheets or physics (Flame has a flame_forge2d integration for rigid bodies). The Flame package API evolves, so follow the version's documentation.

JS A component tree with hitboxes (Flame-style)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

3D models

Flutter's own canvas is 2D, so true 3D takes an extra layer. The easiest way to show a model is model_viewer_plus, which wraps Google's <model-viewer> web component in a WebView (and uses it directly on the web). It loads glTF/GLB files and gives you rotation, zoom and, on supported devices, augmented reality:

DART
const ModelViewer(
  src: 'assets/models/helmet.glb',      // declare the asset in pubspec.yaml
  alt: 'A 3D model of a helmet',
  autoRotate: true,
  cameraControls: true,
  ar: true,
  backgroundColor: Color(0xFF0B1220),
)

It is ideal for a product page. Because it runs inside a WebView, it needs the platform WebView, an internet permission on Android if models load from the network, and it cannot be styled or animated by Flutter widgets. For real-time 3D scenes, game levels or custom shaders, look at flutter_scene (built on Impeller, still evolving), three_dart-style ports, or embedding an engine such as Unity as a view. Keep model files small (compress textures, use Draco or Meshopt compression) so they load fast on mobile.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why multiply movement by dt (delta time)?

    A fixed number of pixels per frame would run twice as fast on a 120 Hz screen.
  2. 2. How does the painter repaint every frame without setState?

    A repaint listenable triggers only repainting of that canvas whenever it notifies.
  3. 3. What does Rect.overlaps check?

    Two axis-aligned rectangles overlap unless one lies fully to one side of the other.
  4. 4. Why clamp dt to a maximum such as 0.05 seconds?

    After a background pause or a slow frame, a large dt would let coins skip through the basket.

Summary

  • A game is a loop: tick, update by dt, paint.
  • Keep rules in a plain class, drawing in a CustomPainter, and wire them with a Listenable for repaints.
  • Use Ticker through SingleTickerProviderStateMixin, and dispose it.
  • Rectangle overlap with Rect.overlaps is enough for many 2D collisions.
  • Clamp dt, seed random numbers for tests, and rebuild only the small widgets that show the score.

Next: Projects: Calculator, BMI, Tic-Tac-Toe, Quiz and Magic 8 Ball