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

寵の児 提交于 2020-04-30 06:37:06

问题


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);
  }
}

回答1:


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);
  }


来源:https://stackoverflow.com/questions/61282624/flutter-update-is-giving-me-this-error-the-method-was-called-on-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!