2D Snake Game in Flutter: Step-by-Step Guide
In this article
This guide shows you how to build a classic 2D Snake game in Flutter from scratch. You'll create a playable game with a moving snake, food to eat, score tracking, and game-over detection. By the end, you'll have a solid understanding of Flutter's game loop, keyboard input, and state management. No prior game development experience is needed, but basic Flutter knowledge (widgets, StatefulWidget) is helpful.
What You'll Need
- Flutter SDK installed and set up (version 3.0 or later recommended)
- An IDE like Android Studio, VS Code, or IntelliJ with Flutter plugins
- A device or emulator to run the app (or use Flutter web)
- Basic understanding of Dart and Flutter widgets
Step-by-Step
- Create a new Flutter project. In your terminal, run:
flutter create snake_game. Then navigate into the project folder:cd snake_game. - Replace the default code. Open
lib/main.dartand delete its contents. You'll write the entire game in this file for simplicity. - Set up the game constants. At the top of
main.dart, define constants for the board size (e.g., 20x20 grid), the tile size (e.g., 20 pixels), and the tick speed (e.g., 200 milliseconds). For example:const int boardSize = 20; const double tileSize = 20; const Duration tickSpeed = Duration(milliseconds: 200); - Create the main app widget. Define a
SnakeGameas aStatefulWidget. In itsbuildmethod, return aMaterialAppwith aScaffoldthat contains the game board widget. - Build the game board widget. Create a
GameBoardwidget that is also stateful. It will hold the game state: the snake's list of positions (each aPoint), the current direction, the food position, and the score. Initialize the snake with three segments in the middle of the board, and place food randomly. - Implement the game loop. In the
initStateofGameBoard, start a periodic timer usingTimer.periodic(tickSpeed, (timer) => _updateGame()). The_updateGamemethod will move the snake, check for collisions, and update the UI. - Move the snake. In
_updateGame, calculate the new head position by adding the current direction vector to the current head. Insert the new head at the front of the snake list. If the new head is on food, increase the score and spawn new food; otherwise, remove the tail segment. - Handle collisions. Check if the new head hits the wall (x or y out of bounds) or hits itself (the head position is already in the snake's body). If so, stop the timer and set a game-over flag.
- Control the snake. Use
FocusandKeyboardListenerto capture arrow keys. In theonKeyEventcallback, change the direction based on the key pressed, but prevent reversing directly (e.g., if moving right, don't allow left). Alternatively, add on-screen buttons for mobile. - Draw the game. In the
buildmethod ofGameBoard, use aCustomPaintwidget with aGamePainterclass that extendsCustomPainter. In itspaintmethod, draw the background, the snake (as green squares), and the food (as a red circle). - Add score and game-over UI. Display the score at the top of the board. When the game is over, show a message like "Game Over" and a restart button. The restart button resets the state and restarts the timer.
- Test the game. Run the app with
flutter run. Use arrow keys to control the snake. Verify that the snake moves, eats food, grows, and the game ends on collision.
Common Mistakes
- Forgetting to cancel the timer when the widget is disposed, causing memory leaks.
- Allowing the snake to reverse into itself, which causes instant death. Always check the opposite direction.
- Not using
setStateafter updating game state, so the UI doesn't refresh. - Off-by-one errors when checking boundaries; remember that board indices go from 0 to boardSize-1.
- Placing food on top of the snake; always check that the random position is not occupied.
Tips
- Use a
Listfor the snake; the head is always the first element. - To make the game more responsive, use a shorter tick speed (e.g., 150ms) for higher difficulty.
- For a smoother experience, consider using
AnimationControllerinstead of a raw Timer, but Timer is simpler for beginners. - Add sound effects or vibration on eating food for extra polish.
- Use
Randomfromdart:mathto generate food positions.
Troubleshooting
If the game doesn't respond to arrow keys, make sure the Focus widget is attached and has autofocus enabled. On mobile, add on-screen buttons because physical keyboards aren't available. If the snake moves too fast or too slow, adjust the tick speed. If you see a black screen, check that your CustomPainter is correctly drawing and that the widget has a non-zero size (wrap in Expanded or AspectRatio). If the game crashes, check for null values in your snake list or food position.
Frequently Asked Questions
How do I change the speed of the snake?
Adjust the Duration in the Timer.periodic. Lower values make the snake move faster.
Can I add levels or increasing difficulty?
Yes, you can decrease the tick speed every time the snake eats a certain number of foods, or increase the board size.
How do I add sound effects?
Use the audioplayers package to play a short sound when the snake eats food or when the game ends.
Is it possible to make the game work on mobile with touch controls?
Yes, add four directional buttons at the bottom of the screen and set the direction on tap.
How do I save the high score?
Use the shared_preferences package to store the highest score locally.
Why does the snake sometimes pass through itself?
This happens if you don't check self-collision correctly. Make sure you check the new head against all body segments except the tail if the tail is about to move.