flutterwindowsflame

Flutter Flame Background image full screen


I'm using the Tick Tack Toe app sample and modified the Play session screen to use a Flame Game widget. I'm trying to set a full screen background image (windows) that will resize when the window resizes. The code below works great if I remove the Game widget and replace with a Container but when using the Game widget the background will not resize. Is there a better way of doing this?

 return Scaffold(
    body: Container(
        width:MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/background1.png"),
            fit: BoxFit.fill,
          ),
        ),
        // Replace the GameScreen with Container and it works as desired
        child: GameScreen(level)));

}


Solution

  • You can try this code, hope it helps:

    class Background extends SpriteComponent with HasGameRef<FlappyBirdGame> {
      Background();
    
      @override
      Future<void> onLoad() async {
        final background = await Flame.images.load("Insert your background here");
        size = gameRef.size;
        sprite = Sprite(background);
      }
    }
    

    Here is "YourGame" class:

    class YourGame extends FlameGame with TapDetector, HasCollisionDetection {
      YourGame();
    
      @override
      Future<void> onLoad() async {
        addAll([
          Background(),
        ]);
      }
    
      @override
      void onTap() {
      }
    
      @override
      void update(double dt) {
        super.update(dt);
      }
    }
    

    And in main.dart file:

    Future<void> main() async {
      SystemChrome.setSystemUIOverlayStyle(
          const SystemUiOverlayStyle(statusBarColor: Colors.transparent));
      WidgetsFlutterBinding.ensureInitialized();
      await Flame.device.fullScreen();
      final game = YourGame();
      runApp(
        GameWidget(
          game: game,
          ...
        ),
      );
    }