Search code examples
flutterdartflame

Flutter update is giving me this error: The method '*' was called on null


I have a flutter app using the flame library. I'm trying to make an object move in a flutter game. When I run the update function, I get the following error:

The method '*' was called on null.
Receiver: null
Tried calling: *(0.0)

Seems like something isn't initialized and the update function is ran before that something is initialized. When I comment out player.update(t) it works, but the update function doesn't get called. What am I doing wrong ad how can I fix it? Here's my code:

Game Controller Class

class GameController extends Game {
  Size screenSize;
  Player player;

  GameController() {
    initialize();
  }

  void initialize() async {
    final initDimetion = await Flame.util.initialDimensions();
    resize(initDimetion);
    player = Player(this);
  }

  void render(Canvas c) {
    Rect bgRect = Rect.fromLTWH(0, 0, screenSize.width, screenSize.height);
    Paint bgPaint = Paint()..color = Color(0xFFFAFAFA);
    c.drawRect(bgRect, bgPaint);

    player.render(c);
  }

  void update(double t) {
    if (player is Player) { // Tried adding this if statement but it didn't work
      player.update(t);
    }
  }

  void resize(Size size) {
    screenSize = size;
  }
}

Player Class

class Player {
  final GameController gameController;
  Rect playerRect;
  double speed;

  Player(this.gameController) {
    final size = 40.0;

    playerRect = Rect.fromLTWH(gameController.screenSize.width / 2 - size / 2,
        gameController.screenSize.height / 2 - size / 2, size, size);
  }

  void render(Canvas c) {
    Paint color = Paint()..color = Color(0xFF0000FF);
    c.drawRect(playerRect, color);
  }

  void update(double t) {
    double stepDistance = speed * t;
    Offset stepToSide = Offset.fromDirection(90, stepDistance);
    playerRect = playerRect.shift(stepToSide);
  }
}

Solution

  • You never initialize the speed attribute of Player to a value. So speed * t in Player.update causes this error.

    Simply initialize the speed attribute in the constructor

      Player(this.gameController) {
        final size = 40.0;
        this.speed = 0;
        playerRect = Rect.fromLTWH(gameController.screenSize.width / 2 - size / 2,
            gameController.screenSize.height / 2 - size / 2, size, size);
      }