The Wild

2D Snake Game in Flutter: Step-by-Step Guide

· 5 min read · Reptiles and Amphibians

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. Create a new Flutter project. In your terminal, run: flutter create snake_game. Then navigate into the project folder: cd snake_game.
  2. Replace the default code. Open lib/main.dart and delete its contents. You'll write the entire game in this file for simplicity.
  3. 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);
  4. Create the main app widget. Define a SnakeGame as a StatefulWidget. In its build method, return a MaterialApp with a Scaffold that contains the game board widget.
  5. Build the game board widget. Create a GameBoard widget that is also stateful. It will hold the game state: the snake's list of positions (each a Point), 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.
  6. Implement the game loop. In the initState of GameBoard, start a periodic timer using Timer.periodic(tickSpeed, (timer) => _updateGame()). The _updateGame method will move the snake, check for collisions, and update the UI.
  7. 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.
  8. 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.
  9. Control the snake. Use Focus and KeyboardListener to capture arrow keys. In the onKeyEvent callback, 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.
  10. Draw the game. In the build method of GameBoard, use a CustomPaint widget with a GamePainter class that extends CustomPainter. In its paint method, draw the background, the snake (as green squares), and the food (as a red circle).
  11. 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.
  12. 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 setState after 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 List for 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 AnimationController instead of a raw Timer, but Timer is simpler for beginners.
  • Add sound effects or vibration on eating food for extra polish.
  • Use Random from dart:math to 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.