Skip to main content

correct-game-instantiating

added in: 5.6.0
warning
🛠

Warns when a game is instantiated in a stateless widget build method.

Instantiating game in a stateless widget build method cases the game to reset every time Flutter rebuilds the widget.

Example

❌ Bad:

class MyGamePage extends StatelessWidget {

Widget build(BuildContext context) {
return GameWidget(game: MyFlameGame()); // LINT
}
}

✅ Good:

class MyGamePage extends StatefulWidget {

State<MyGamePage> createState() => _MyGamePageState();
}

class _MyGamePageState extends State<MyGamePage> {

late final _game = _MyFlameGame();


Widget build(BuildContext context) {
return GameWidget(game: _game);
}
}

or:

class MyGamePage extends StatelessWidget {

Widget build(BuildContext context) {
return GameWidget.controlled(gameFactory: MyFlameGame.new);
}
}