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

12. Show Game Over Dialog

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: 11. Detecting Collisions Next episode: 13. Restarting the Game

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.

Notes: 12. Show Game Over Dialog

Add detectCollision to the getNextPosition method.

Transcript: 12. Show Game Over Dialog

In this episode, you will be using the provided showGameOverDialog method to display a game-over dialog to the user when the Snake collides with the play-area boundaries. The showGameOverDialog method is provided as part of the starter project.

Let’s begin.

In the getNextPosition method, once you have detected a collision, instead of just returning the original position, we need to invoke the showGameOverDialog method.

Offset getNextPosition(Offset position) {
    ...
    if (detectCollision(position) == true) {
        if (timer != null && timer.isActive) timer.cancel();
        showGameOverDialog(); // Add this
        return position;
    }
    ...
    return nextPosition;
}

Let’s a little bit of delay before we display the game-over dialog to the user after we detect the collision.

Let’s make some changes to the code we have just implemented.

First, you need to make the return type of the getNextPosition method a Future<Offset> rather than just Offset.

Next, we wrap the showGameOverDialog with a Future.delayed with a small duration of 500ms or so. Also, add an await keyword to wait for the Future to complete.

Future<Offset> getNextPosition(Offset position) async {
    ...

    if (detectCollision(position) == true) {
      if (timer != null && timer.isActive) timer.cancel();
      await Future.delayed(Duration(milliseconds: 500), () => showGameOverDialog());
      return position;
    }
    ...
}

Finally, you need to make some changes where you have used getNextPosition method. Add await keyword before getNextPosition in the draw method like this.

void draw() async {
    ...
    // Update this
    positions[0] = await getNextPosition(positions[0]);
}

That’s all.

Save all the files and retstart the app completely.

If the Snake collides with the play-area boundaries, you should see a game-over dialog. Nice, right? However, if you tap on the Restart button in the dialog, it does not quite restart the game. Let’s fix that in the next episode.