Flame engine architecture and gotchas
flameflutterdartgame-enginecollisioncomponents
Flame is the 2D game engine for Flutter: a game loop, a component tree, a camera, and a collision broadphase (including a QuadTree). This article covers how to structure a Flame game and the engine behaviors that bit Run, Justin's speedrun platformer. Rendering costs are in Flutter / Flame canvas rendering performance facts.
Architecture choices
- Flame Component System (FCS) is the right default: hierarchical parent/child
components, mixins for cross-cutting concerns (
HasGameReference,CollisionCallbacks). Lifecycle:onLoad(once, async) ->onMount(each add) ->update/render->onRemove. Weakness: logic and data coupled in one class grows god components (Run'sGameWorld,Player, editor screen each passed 600-2000 lines before managers were extracted: CheckpointManager, DeathManager, DimensionManager, GhostManager, RotationManager). - ECS (
flame_oxygen): minimally maintained, pays off only around 5000+ entities, and loses QuadTree/camera/HUD integration. Dart's GC makes cache-friendly layouts matter less than in C++/Rust. Not recommended for a few hundred entities. - BLoC / clean architecture (flame_bloc, flame_behaviors): fine for menus and settings, adds latency and ceremony for 60 fps gameplay state.
- Three-tier state rule: frame-critical state (position, velocity) lives in plain component fields, never in a state-management library; UI state uses normal Flutter state; cross-cutting services (audio, prefs, API) are called directly.
- Long term, keep physics out of Flame callbacks entirely: a pure-Dart simulation layer with Flame only rendering (Fixed-timestep game loop for browser games).
Collision gotchas
- Passive vs passive pairs are never generated. If two things must detect each other,
at least one must be
CollisionType.active. Run's spike-strip ability and the chaser hazard were both passive, so the strip never stopped chasers (fixed by making the strip active). - Contacts arrive one frame late: integrating in
update()and resolving inonCollisionmeans resolution is order dependent and a frame behind. - Collision detection runs once per frame after all updates, so substepping inside
update()does nothing for collisions (Collision tunneling (fast objects passing through walls)). game.collisionDetection.raycast()is QuadTree backed and works well for projectiles and anti-tunneling checks.- Overlapping zones: if each zone's exit sets
windForce = 0, leaving one of two overlapping wind zones cancels both. Track effects per source (enterWind(src, f)/leaveWind(src)) and sum them.
Lifecycle gotchas
- Never add or remove components inside
update()of a sibling iteration; set a deferred flag and apply it at a safe point. Multiple deferred flags (pending level load, dimension switch, rotation) can overwrite each other in one frame; use a queue or priority. GameWidgetremoval does not reliably call your world'sonRemove()when youNavigator.popaway. Stop music and other side effects explicitly before navigating (Run's stale gameplay track bug).- Stream subscriptions (e.g. gamepad events) created in a component that survives level restarts stack up unless cached and reused.
- Track every component spawned from level data in one list and remove exactly those on
rebuild. Run's hand-maintained "types to remove" list missed
AbilityItem, which then duplicated on every death.
Input
- Gameplay keys:
HasKeyboardHandlerComponentson the game andKeyboardHandleron components; you cannot mix it withKeyboardEventson the same game.GameWidgetautofocuses, and focus returns after overlays close (Flame 1.4+). - Editor/menu shortcuts belong to Flutter: see Keyboard shortcuts and focus in Flutter.
Misc
- Camera: use
CameraComponent(the oldCamerais deprecated);CameraComponent.withFixedResolutiongives a fixed logical viewport with letterboxing. flame_tiledSpriteBatch shows seams unless tileset exports have 1-2 px extrusion.- There is no mature Flame multiplayer library (see Live ghost-racing multiplayer (design research)).
Gotchas from Spacebar (Flutter build, 2026-03 to 07)
- Riverpod writes during
update()crash or misbehave: Flame'supdate()runs inside Flutter'sLayoutBuilder, so provider writes must be deferred withaddPostFrameCallback. Aflame_riverpodstartup crash (null ref in deferred actions) came from this. Throttle provider ticks (10 Hz) so HUD values do not rebuild widgets every frame. flame/game.dartdoes not exportPositionComponent; importcomponents.darttoo.PolygonHitboxtakes the raw vertex list (List<Vector2>), not a size and position.- Flame's removed bit propagates to descendants (verified in the package source), so a
system holding references can prune with
isRemoved. - Components parented to a world chunk need
isMountedguards in async callbacks (e.g.shop.loaded.then(...)), or they spawn "ghost" children after the chunk unloads. - A component reading
parent?.parentwhere it meantparentsilently skipped AI terrain damage; when an effect works for the player but not AI, check the tree path. flutter testpiped into another command swallows its exit code; read the output.
See also
- Visual effects in Flame (particles, effects, decorators, shaders)
- Flutter app architecture, state management and packages (2026 survey)
- Flutter / Flame canvas rendering performance facts
Linked from
- Collision tunneling (fast objects passing through walls)
- Fixed-timestep game loop for browser games
- Flutter / Flame canvas rendering performance facts
- Flutter and Dart gotchas (collections, widgets, theming)
- Flutter app architecture, state management and packages (2026 survey)
- Hazards and counter-abilities in a speedrun platformer
- Keyboard shortcuts and focus in Flutter
- Run (runrunrunrun.run), Justin's speedrun platformer