Flutter更新给了我这个错误:方法'*'在null上被调用 [英] Flutter update is giving me this error: The method '*' was called on null

查看:239
本文介绍了Flutter更新给了我这个错误:方法'*'在null上被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 flame 库的flutter应用程序。我正在尝试使物体在颤动游戏中移动。当我运行 update 函数时,出现以下错误:

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)

似乎有些东西未初始化,并且在初始化之前先运行 update 函数。当我注释掉 player.update(t)时,它可以工作,但不会调用更新功能。我在做错广告时该怎么解决?这是我的代码:

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:

游戏控制器类

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

播放器类

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


推荐答案

您永远不要将Player的speed属性初始化为一个值。因此,Player.update中的 speed * t 会导致此错误。

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

只需在构造函数中初始化speed属性

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

这篇关于Flutter更新给了我这个错误:方法'*'在null上被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆