flutterdartflame

Flutter flame : var and kdebugmode


In this code (main.dart):

   void main() {
  WidgetsFlutterBinding.ensureInitialized();

  Flame.device.fullScreen();
  Flame.device.setLandscape();

  RunAdventure game = RunAdventure();

  runApp(GameWidget(game: kDebugMode ? RunAdventure() : game));
}

And this file (run_adventure.dart):

import 'package:flame/game.dart';

class RunAdventure extends FlameGame {

}

I am a beginner and I don't understand the purpose of the first "RunAdventure" in this line: "RunAdventure game = RunAdventure();". What will it change in the rest of my code? Isn't it equivalent to writing "var game = RunAdventure();" (even though I know that's not good)? I would just like to understand what it changes.

Another question, is it necessary to use kDebugMode? Isn't hot reload enough? And what does it change to write "Runadventure()" and not "game", because game == RunAdventure() no ?

Thanks


Solution

  • In the video tutorial you are following you mentioned that they explained why they did that at 8:28, let me try to clarify what they mean.

    It is actually quite a neat trick. Since all the components in the game widget isn't following the normal rules of hot reload like widgets do, this trick makes sure that a new game is instantiated every time that you do a hot reload, so that you're not accidentally stuck with an old state in the game. Since the code is never changing when kDebugMode isn't true you can always use the same game instance.

    What I don't understand is what changes between "RunAdventure()" and "game" given that it's the exact same variable since "game = RunAdventure();"?

    The part inside of runApp is controlled by hot reload, meanwhile the part outside of it is not, so here it will re-create the game all the time on hot reload meanwhile if the variable is defined outside of runApp it will use the same instance even though the app has been hot reloaded.

    I am a beginner and I don't understand the purpose of the first "RunAdventure" in this line: "RunAdventure game = RunAdventure();". What will it change in the rest of my code? Isn't it equivalent to writing "var game = RunAdventure();

    var uses the type inference of Dart, meanwhile RunAdventure game = RunAdventure(); specifies specifically which type it is going to be. Since this variable isn't going to be mutable a third option is actually preferred:

    final game = RunAdventure();