flutter build web creates a nested assets folder so images are not loaded

497 Views Asked by At

from pubspec.yaml:

flutter:
  assets:
    - assets/images/
  fonts:
    - family: NunitoSans
      fonts:
        - asset: assets/fonts/NunitoSans-Regular.ttf
        - asset: assets/fonts/NunitoSans-Bold.ttf
        - asset: assets/fonts/NunitoSans-ExtraBold.ttf
  generate: true

folders in root: [![enter image description here][1]][1]

image code:

Image.asset(
              'assets/images/temp.jpg',
              height: height * 0.5,
              width: width * 0.4,
              fit: BoxFit.fill,
            )

folders after flutter build web: [![enter image description here][2]][2]

The browser tries to get images from <domain>/assets/images/<image_name> [1]: https://i.stack.imgur.com/wPAYe.png [2]: https://i.stack.imgur.com/jDUNo.png

1

There are 1 best solutions below

0
On

I've been having the same issue while deploying a website using an S3 bucket and CloudFront from AWS.

From what I've found on the internet, it's a known problem, but it has not been looked into much details by flutter dev's due to the lack of information on the problem from people who asked the question previously.

However, I've found a work around that work for me:

[1] In the pubsec.yaml file of the flutter project;

flutter:
  assets:
    - assets/images/

[2] In the dart code;

AssetImage('assets/images/your_image.png')

Since AssetImage already looks into the assets you've defined in the pubsec.yaml file, you shouldn't need the assets/ in front of the path. But after adding it, the request made by the browser to recover the Image becomes <domain>/assets/assets/images/<image_name> in my case.

Which doesn't require to modify what flutter is creating with flutter build web, and also, still works in the development environment of flutter.