Setting Up Flutter and Flame

Setting Up Flutter and Flame

Before building a Flutter web game, you must prepare your development environment correctly. A good setup saves time, prevents errors, and makes game development much easier. In this chapter, you will learn how to install Flame, connect it with Flutter, run your game in the browser, and understand the basic project structure used in Flame games.

Many beginners try to build games immediately without understanding how Flutter and Flame work together. Flutter handles the application and rendering system while Flame adds game features such as sprites, collision detection, game loops, animations, and input handling.

By the end of this chapter, you will have a working Flame project running inside the browser and you will understand the important files used in every Flutter web game project.

Adding Flame to Your Flutter Project

The first step is installing Flame into your Flutter project. Flame is added using the Flutter package manager called pub.

Open your terminal inside the Flutter project folder and run this command.

flutter pub add flame

This command downloads Flame and connects it to your project. Flutter stores external packages inside the pubspec.yaml file automatically.

After installation finishes, you can start using Flame classes inside your Dart files.

Checking the pubspec.yaml File

Open the pubspec.yaml file in your project. You will see Flame added under dependencies.

dependencies:
  # This section lists all the packages used in the project
  flutter:
    sdk: flutter
  # This is the Flame game engine package
  flame: ^1.18.0

The version number may be different depending on the latest Flame release.

This file is very important in every Flutter project because it controls packages, assets, fonts, and project settings.

Creating a Basic Flame Game

Now let us create the simplest possible Flame game.

Open the lib folder and replace the contents of main.dart with this code.

import 'package:flame/game.dart';
import 'package:flutter/material.dart';

void main() {
  // The runApp function starts your Flutter application
  runApp(
    // GameWidget is used to display the Flame game
    GameWidget(
      game: MyGame(),
    ),
  );
}

// This is your custom game class
class MyGame extends FlameGame {

}

This creates a very basic Flame game connected to Flutter.

The runApp function starts the Flutter application.

GameWidget is a special Flame widget that displays the game on the screen.

MyGame is your custom game class where game logic will be written.

Understanding FlameGame

FlameGame is the main base class used in many Flame projects.

It already contains important game systems such as rendering, update cycles, component management, and timing systems.

Instead of building these systems manually, developers extend FlameGame and add their own logic.

Think of FlameGame as the main controller of the entire game.

Running the Game on Web

Flutter makes web deployment very easy. To run the game in the browser, use this command inside the terminal.

flutter run -d chrome

Flutter will compile the project and open it inside Google Chrome.

If everything is working correctly, you will see a blank screen. Even though nothing is visible yet, your Flame game is already running.

Why the Screen Looks Empty

Many beginners think something is broken when they see a blank screen.

The screen is empty because no game objects or drawings were added yet.

Your game exists but there is nothing to render on the screen.

In the next example, you will draw text to confirm that the game is active.

Adding Text to the Game

Flame provides rendering methods for drawing text, shapes, and images.

Update the game class with this code.

import 'dart:ui';

import 'package:flame/game.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(
    GameWidget(
      game: MyGame(),
    ),
  );
}

class MyGame extends FlameGame {

  @override
  // The render method handles drawing graphics on the screen
  void render(Canvas canvas) {
    super.render(canvas);

    // TextPainter is used to draw text on the canvas
    final textPainter = TextPainter(
      text: const TextSpan(
        text: 'My First Flame Game',
        style: TextStyle(
          color: Colors.white,
          fontSize: 32,
        ),
      ),
      textDirection: TextDirection.ltr,
    );

    // Prepare the text layout before drawing
    textPainter.layout();

    // Draw the text at position 100 100
    textPainter.paint(
      canvas,
      const Offset(100, 100),
    );
  }
}

This code draws text directly onto the game canvas.

The render method is called many times every second by the game engine.

Canvas is the area where all game graphics are drawn.

Understanding the Render Method

Rendering means drawing objects on the screen.

The render method controls visual output inside the game.

Every frame, Flame clears the screen and redraws all visible objects again.

This process happens extremely fast which creates smooth animations and movement.

Understanding the Update Method

Another important method inside Flame is update.

The update method handles game logic.

Player movement, timers, enemy behavior, and physics calculations are usually placed inside update.

Here is a simple example.

class MyGame extends FlameGame {

  double playerX = 0;

  @override
  // The update method handles game logic and movement
  // The dt value means the time passed since the last frame
  void update(double dt) {
    super.update(dt);

    // Move the player position by 100 pixels every second
    playerX += 100 * dt;
  }
}

The dt value means delta time.

Delta time represents the amount of time passed since the previous frame.

Using delta time keeps movement smooth across different devices and screen refresh rates.

Project Structure for Flame Games

Organizing your files properly is very important for large games.

A messy project becomes difficult to maintain later.

Here is a common folder structure used in Flame projects.

lib/
  main.dart
  game/
    my_game.dart
  player/
    player.dart
  enemies/
    enemy.dart
  ui/
    hud.dart
assets/
  images/
  audio/

The game folder contains the main game logic.

The player folder contains player related classes.

The enemies folder stores enemy systems.

The ui folder contains interface elements such as score displays and buttons.

Adding Assets to the Game

Games use images, sounds, music, and animation files called assets.

Flutter requires assets to be registered inside pubspec.yaml.

Example configuration.

flutter:
  # This section registers assets like images and audio
  assets:
    - assets/images/
    - assets/audio/

Without this step, Flutter cannot access your game files.

Loading an Image in Flame

Flame makes image loading easier than raw Flutter drawing.

Example image loading code.

@override
// The onLoad method runs once when the game starts
Future<void> onLoad() async {
  // Load an image from the assets folder
  final image = await images.load('player.png');
}

The onLoad method runs before the game starts.

It is commonly used for loading assets and preparing game data.

Why Async Loading Matters

Loading assets takes time.

Large images and audio files cannot load instantly.

Async loading prevents the game from freezing while files are loading.

This creates a smoother experience for players.

Understanding GameWidget

GameWidget is the connection between Flutter and Flame.

Flutter normally displays buttons, screens, and layouts.

Flame games need a drawing surface where rendering can happen continuously.

GameWidget provides that surface.

It also helps handle resizing, focus, lifecycle events, and overlays.

Common Beginner Mistakes

One common mistake is forgetting to register assets inside pubspec.yaml.

Another mistake is writing wrong asset paths.

Some beginners also forget to run flutter pub get after changing dependencies.

Another common issue happens when Chrome caching causes old versions of the game to appear.

Refreshing the browser or restarting Flutter usually fixes this.

Conclusion

Setting up Flutter and Flame is the foundation of web game development. Once your environment is ready, you can begin creating interactive games with graphics, movement, animations, collisions, and sound.

In this chapter, you learned how to install Flame, create a basic game class, run the game in Chrome, organize files, register assets, and understand the main game methods used in Flame projects.

In the next chapter, you will create your first real web game and start adding visible game objects to the screen.

← Previous Chapter Next Chapter 4 →