Search code examples
flutterdartgame-engineflame

error: Non-nullable instance field 'screenSize' must be initialized


I am pretty new to flame and flutter but I was just trying to set up the basis for a game project I am working on and it is telling me that the field "screenSize", as well as "tileSize", must be initialized.

import 'dart:ui';

import 'package:flame/flame.dart';
import 'package:flame/game.dart';
import 'package:flutter/cupertino.dart';

class GameController extends Game {
  Size screenSize;
  double tileSize;

  GameController() {
    initialize();
  }

  void initialize() async {
    resize(await Flame.util.initialDimensions());
  }

  @override
  void render(Canvas canvas) {
    Rect background = Rect.fromLTWH(0, 0, screenSize.width, screenSize.height);
    Paint backgroundPaint = Paint()..color = Color(0xFFFAFAFA);
    canvas.drawRect(background, backgroundPaint);
  }

  @override
  void update(double t) {}

  void resize(Size size) {
    screenSize = size;
    tileSize = screenSize.width / 10;
  }

  void onTapDown(TapDownDetails d) {
  }
}

Solution

  • If you are new to Flame, extend BaseGame and not Game. BaseGame will give you everything you need from the game engine meanwhile with Game you have to implement everything yourself.

    You can check a basic example here, and there are some more examples on https://examples.flame-engine.org/

    There are some good tutorials on YouTube too.

    Flawn's answer is correct about the values having to be initialized too, but in BaseGame you would automatically have the size of the screen.