Quoc
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    ## Beyond Widgets: A Journey into Game Development with Flutter and Flame 🔥 Last week, we had the fantastic opportunity to share one of our passions with our colleagues: using Flutter for game development with the **Flame engine**. The energy in the room was incredible, and it was exciting to see so many developers, accustomed to building slick business apps, get a glimpse of a completely different world—all within the framework they already know and love. This post is a recap of that session, for anyone in the wider community curious about taking their Flutter skills to the next level. ### I. Introduction: Why Bother with Games in Flutter? For most, Flutter is the go-to for building beautiful, high-performance, cross-platform applications. But what happens when you want to move beyond static screens and user input forms? What if you need a constant update cycle, physics, and complex animations? That's where game development comes in. While you *could* build a simple game using Flutter's animation controllers and widgets, you'd quickly find yourself reinventing the wheel. You need a **game loop**, a way to handle **sprites**, **collision detection**, and an architecture designed for performance under constant change. This is the problem **Flame** solves. It's not a separate framework but a minimalist 2D game engine that lives *inside* Flutter. It directly leverages Flutter's modern rendering pipeline—powered by the **Impeller** engine on mobile—to deliver smooth, high-frame-rate graphics. It gives you the best of both worlds: the development speed of Flutter and the power of a dedicated game engine. ### II. Case Studies: Seeing is Believing To truly evaluate the power of Flutter and Flame, it helps to see what's already been built. While Flutter is known for its productivity apps, it's also powering some truly engaging interactive experiences. Let's look at a few examples, some of which you might recognize from the official Flutter games showcase: <center><img width=80% src="https://i.ibb.co/ycqWxBRb/image.png" alt="flutter showcase"/></center> These examples, from high-fidelity experiences to casual fun, showcase the breadth of possibilities—from graphically rich multiplayer games to engaging casual experiences, all built with Flutter. At our company, we've also dipped our toes into "game-like" applications, even if they aren't traditional arcade or action games. Consider our applications: - Home Building ([Sumica app](https://sumica.ai/)'s Utility) - [DeBingo](https://v2.debingo.app/) - [LuckyPool](https://luckypool.cc/) <center><img width=80% src="https://i.ibb.co/1YYDkhDz/image.png" alt="wkm products"/></center> The key distinction lies in how they run. Our existing apps are primarily event-driven—they react to user input or triggers. In contrast, a Flame game runs on a constant, real-time game loop. ### III. How Flame Works: A Deep Dive into the Architecture <center><img width=80% src="https://i.ibb.co/Cr2LVs7/image.png" alt="flame core"/></center> So, how does Flame actually turn Flutter widgets into a high-performance game canvas? > Where Flutter has `Widget`s, Flame has `Component`s. Where Flutter apps consist of creating trees of widgets, Flame games consist of maintaining trees of components. > > Therein lies an interesting difference between Flutter and Flame. Flutter's widget tree is an ephemeral description that is built to be used to update the persistent and mutable `RenderObject` layer. Flame's components are persistent and mutable, with an expectation that the developer will use these components as part of a simulation system. > > Flame's components are optimized for expressing game mechanics. [-Flutter Cookbook-](https://codelabs.developers.google.com/codelabs/flutter-flame-brick-breaker#3) The magic lies in two fundamental concepts that are cornerstones of modern game development: the **Game Loop** and a **Component-Based Architecture**. Let's break down exactly what these are and how they work in Flame. #### 1. The Game Loop: The Heartbeat of Your Game At its core, every game is an illusion of motion, created by drawing a series of images to the screen very quickly. The **Game Loop** is the engine that drives this illusion. It's a simple, infinite loop that performs two critical tasks on every single "tick" or frame: 1. **`update()`**: Handle the logic. This is where you move characters, check for player input, calculate physics, and update health points. It's the "thinking" part of the frame. 2. **`render()`**: Draw the results. After all the logic is calculated in `update`, this step takes the final state of all game objects and draws them to the screen. Flame abstracts this entire process away for you inside its `FlameGame` class. You simply need to override two key methods: `update(double dt)` and `render(Canvas canvas)`. - `update(double dt)`: The `dt` (delta time) argument is crucial. It represents the time, in seconds, that has passed since the last frame. By multiplying all movements by `dt`, you ensure your game runs at the same speed regardless of the device's frame rate. A character moving at `100` pixels per second will cover the same distance on a device running at 60 FPS as it does on one running at 120 FPS. - `render(Canvas canvas)`: This provides you with a low-level `Canvas` object from `dart:ui`. This is the API Flutter uses for drawing, which is then executed by the underlying rendering engine (**Impeller** on modern mobile platforms). ***Game Loop Example*** Here's a basic example of a `FlameGame` that moves a white square across the screen. This code demonstrates the loop in its purest form: ```dart class MyGame extends FlameGame { // Speed of the square in pixels per second final double speed = 200.0; late Rect square; final Paint whitePaint = Paint()..color = const Color(0xFFFFFFFF); // This is called once when the game is first loaded. @override Future<void> onLoad() async { // Initialize the square's starting position and size. square = Rect.fromLTWH(50, 50, 100, 100); } // This is called on every frame, before render. @override void update(double dt) { super.update(dt); // Don't forget to call super.update() // Move the square to the right, scaled by delta time. square = square.translate(speed * dt, 0); // If the square goes off the right side of the screen, reset it to the left. if (square.left > size.x) { square = square.translate(-size.x - square.width, 0); } } // This is called on every frame, after update. @override void render(Canvas canvas) { super.render(canvas); // Don't forget to call super.render() // Draw the current state of the square onto the canvas. canvas.drawRect(square, whitePaint); } } ``` While this works, managing hundreds of objects this way would be a nightmare. That's why Flame uses a Component system. #### 2. Component Entity System (CES): Building Games with LEGOs The `update`/`render` loop is powerful but low-level. To manage complexity, Flame uses a **Component Entity System (CES)**. Instead of creating massive classes that inherit tons of functionality (a "God Object"), you build game entities through **composition**. Think of it like building with LEGOs: - An **Entity** is your creation (e.g., a car, a spaceship). In Flame, this is just a `Component`. - **Components** are the individual bricks that give it properties and behavior (e.g., wheels, wings, an engine, a laser cannon). In Flame, your `Player`, `Enemy`, and `Bullet` are all `Component`s. You then give them functionality by adding other, more specialized `Component`s as children. - Want it to have a position and be visible on screen? Extend `PositionComponent`. - Want it to have an animated sprite? Add a `SpriteAnimationComponent` as a child. - Want it to detect collisions? Add a `RectangleHitbox` as a child. This approach is incredibly flexible. Need to give an enemy the ability to shoot? Just add a `ShootingBehaviorComponent`. You don't need to rewrite the entire `Enemy` class. ***Component-Based Example: A Player Character*** Let's create a `Player` component that has visuals and can detect collisions. Notice how the `Player` class itself is a `PositionComponent`, and in its `onLoad` method, it composes its full functionality by adding other specialized components (`SpriteComponent`, `RectangleHitbox`) as children. ```dart // The Player is an "Entity" built from multiple components. // It has a position, size, and can detect collisions. class Player extends PositionComponent with CollisionCallbacks { static final Vector2 initialSize = Vector2(60, 90); final double speed = 300.0; Player() : super(size: initialSize); @override Future<void> onLoad() async { // 1. Add a visual component as a child. // This component will be rendered at the Player's position. final sprite = await Sprite.load('player_sprite.png'); add(SpriteComponent( sprite: sprite, size: size, // Match the parent's size )); // 2. Add a collision hitbox as a child. // This component handles collision detection for the Player. add(RectangleHitbox()); } // This callback is automatically triggered by the collision system // when the RectangleHitbox collides with another. @override void onCollisionStart(Set<Vector2> intersectionPoints, PositionComponent other) { super.onCollisionStart(intersectionPoints, other); if (other is Enemy) { print('Collision with enemy detected!'); // Here you would add logic to take damage, etc. } } // Public method to be called from the main game loop to move the player. void move(Vector2 direction, double dt) { // The PositionComponent handles the position update. position.add(direction * speed * dt); } } ``` By combining the **Game Loop** with a **Component-Based Architecture**, Flame gives you the best of both worlds: the raw power and control of a continuous update/render cycle, and a clean, scalable, and reusable system for building and managing your game world. ### IV. The Verdict: Pros & Cons No technology is perfect, and it's important to be realistic. **✅ Pros:** - **Massive Code Reuse:** Share your game logic across iOS, Android, web, and desktop. - **Amazing Developer Experience:** If you love Flutter, you'll feel right at home. - **Access to Flutter Ecosystem:** Easily integrate maps, authentication, databases, and thousands of other packages. - **Excellent Performance:** For 2D games, Flutter's Impeller-based rendering is more than powerful enough. **❌ Cons:** - **Not for High-Fidelity 3D:** Flame is a 2D-first engine. For complex 3D, which requires advanced shaders and lighting, native engines like Unity or Unreal are still the better choice. - **Smaller Community:** While growing fast, the community and third-party asset library are smaller than those of established engines. You may need to build more things from scratch. - **Ecosystem is Maturing:** While you can leverage the entire Flutter ecosystem, some game-specific tooling (like visual editors) is still under active development. ### V. Interactive Session: The `wkmroyale` Playtest <center><img width=80% src="https://i.ibb.co/1G0XYRnj/With-Frame-shot.png" alt="wkmroyale"/></center> Finally, we ended the session with a company-wide playtest of **wkmroyale**, a real-time, multiplayer battle royale game we have been building with Flutter and Flame. Seeing everyone jump into the game on their phones, running around and competing in real-time, was the ultimate proof of concept. The buzz and excitement as people battled it out was the perfect way to end the presentation. <center><img width=80% src="https://i.ibb.co/pN5Yj35/IMG-5945.jpg" alt="wkm lobby"/></center> The Q&A session that followed was fantastic, with sharp questions about performance optimization, server architecture, and the future of game development in Flutter. Our key takeaway is this: **Flutter and Flame are ready for prime time.** It's a powerful, and incredibly fun stack for building a huge variety of 2D games. If you're a Flutter developer looking for a new challenge, we can't recommend it more. 🚀

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully