Search code examples
flutterdartflame

Adding background in flutter


What should I do to apply my background image in my project? Did I miss something? My background image found under lib/assets/background.jpg

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  Util flameUtil = Util();
  await flameUtil.fullScreen();
  await flameUtil.setOrientation(DeviceOrientation.portraitUp);

  LangawGame game = LangawGame();
  runApp(game.widget);
}

langaw-game.dart

class LangawGame extends Game {
  Size screenSize;
  double tileSize;
  @override
  void render(Canvas canvas) {
    body:
    Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/background.jpg"),
          fit: BoxFit.cover,
        ),
      ),

    );
  }

  @override
  void update(double t) {}
  @override
  void resize(Size size) {
    super.resize(size);
    screenSize = size;
    tileSize = screenSize.width / 9;
  }
}

This is the result

enter image description here

This is the background

enter image description here

i dont have error receive but the image didnt refect


Solution

  • Your image path is not correct. Now your image is under lib/assets folder, but you are trying to access assets/background.jpg. You need to edit with a full path like following:

    AssetImage("lib/assets/background.jpg"),
    

    Note: Also, check your pubspec.yaml file.

    flutter:
      # The following line ensures that the Material Icons font is
      # included with your application, so that you can use the icons in
      # the material Icons class.
      uses-material-design: true
    
      # To add Flutter specific assets to your application, add an assets section,
      # like this:
      assets:
        - lib/assets/background.jpg
    
    

    Read more from the official document.