This article has been archived and is no longer being updated. It may not work with the most recent OS versions.
Building Games in Flutter with Flame: Getting Started
Oct 21 2021
, Dart 2.13, Flutter 2.2, VS CodeDart 2.13, Flutter 2.2, VS Code
Learn how to build a beautiful game in Flutter with Flame. In this tutorial, you’ll build a virtual world with a movable and animated character.
By Vincenzo Guzzi.
Because RayWorld is built with Flutter, it can also run as a web app. Generally, for web games, people want to use keyboard input instead of a joypad. Flame has an interface called KeyboardEvents you can override in your game object to receive notification of keyboard input events.
For this bonus section, you’ll listen for keyboard events for the up, down, left and right arrows, and use these events to set the player’s direction.
Start by adding the mixin KeyboardEvents to the end of your RayWorldGame class declaration, next to HasCollidables.
Add the input import above RayWorldGame:
import'package:flame/input.dart';
Now, override the onKeyEvent method:
@override
KeyEventResult onKeyEvent(RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed) {
final isKeyDown = event is RawKeyDownEvent;
Direction? keyDirection = null;
// TODO 1// TODO 2returnsuper.onKeyEvent(event, keysPressed);
}
Replace // TODO 1 with logic to read RawKeyEvent and set the keyDirection:
The player’s direction is being updated if a key is being pressed, and if a key is lifted the players direction is set to Direction.none if it is the active direction.
Launch your game on the web or an emulator, and you’ll now be able to run around using the W, A, S and D keys on your keyboard.
Where to Go From Here?
You can download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.
You now have all the tools to make a complete 2-D game using the Flame Engine. But why stop there? You could try adding:
More game UI: Incorporate UI elements such as a player health bar, an attack button and a jump button. You could build these using a Flame component or a Flutter Widget.
Enemies: Populate RayWorld with enemies such as goblins or aggressive animals that could attack your player.
Different levels: Load new world sprites and tile maps into your game as the player leaves the area.
Check out the awesome-flame GitHub repository to see what games have already been developed using the Flame Engine and to read some other great Flame tutorials.
As Flame v1.0.0 edges closer to an official release, there’s sure to be plenty of new and exciting game development API’s that take advantage of the Flutter ecosystem. Stay tuned to raywenderlich.com for more great game development tutorials as the release is rolled out!
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.