How to Create a 2D Snake Game in Flutter

Jan 17 2023 · Dart 2.17, Flutter 3.0, Android Studio or VS Code

Part 1: How to Create a 2D Snake Game in Flutter

03. Understanding the Starter Project

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 02. Basics of 2D Rendering Next episode: 04. Create Piece Positions

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

In this video, you will learn about the code provided to you as part of the starter project. There is a few widgets and some utility methods that are available and you will be using them while building the game. Let’s have a look at these widgets and methods one by one.

final int posX, posY;
final int size;
final Color color;
final bool isAnimated;

roundToNearestTens

Assuming that the Snake moves one step length at a time, this method is a mathematical utility that is used to round off the passed integer argument to the nearest step value.

x roundToNearestTens(x)
2 10
8 10
12 10
18 10
22 20
34 30

getRandomPositionWithinRange

This method generates a random position on the screen within the bounds of the play area. You’ll use this function to spawn a new snake when a new game starts and to render a new food for the snake an a random location everytime the Snake eats the food.

showGameOverDialog

showGameOverDialog displays a styled dialog pop-up widget when the Snake collides with any of the boundaries of the play area. This dialog displays

getRandomDirection

getRandomDirection randomly returns one of the four directions: up, down, left or right. You primarily use this function to move the Snake in a random direction when it spawns. It also optionally takes an argument that specifies whether you want the random direction it returns to be horizontal or vertical.

getPlayAreaBorder

This is method that draws a border along the edge of the screen to represent the play area where the Snake moves. If the Snake collides with this boundary, the game is over.