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

11. Detecting Collisions

Episode complete

Play next episode

About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 10. Consuming & Regenerating the Food Next episode: 12. Show Game Over Dialog

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

Take your career further with a Kodeco Pro subscription. 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.

This video Detecting Collisions was last updated on Jan 17 2023

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

You are now able to control a moving Snake. It also grows as it eats the food but one thing that you should also do is prevent the Snake from moving off the screen.

  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Color(0XFFF5BB00),
        child: Stack(
          children: [
bool detectCollision(Offset position) {
bool detectCollision(Offset position) {
    if (position.dx >= upperBoundX && direction == Direction.right) {
        return true;
    } else if (position.dx <= lowerBoundX && direction == Direction.left) {
        return true;
    } else if (position.dy >= upperBoundY && direction == Direction.down) {
        return true;
    } else if (position.dy <= lowerBoundY && direction == Direction.up) {
        return true;
    return false;
Future<Offset> getNextPosition(Offset position) async {
    Offset nextPosition;

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


    return nextPosition;