How can I display Asset Images on Flutter web?

Issue

When I try to display an asset in Flutter Web using the following syntax, no image is shown:

Image.asset(
  'assets/image.png',
)

On mobile, the same code will show an image.

The structure is as follows:

assets
  image.png
lib
  ...
pubspec.yaml

In the Pubspec, I declare the asset like this:

flutter:
  assets:
    - assets/image.png

Solution

All assets are stored in an assets directory in Flutter Web, which means that the image asset will be stored like this on web:

assets
  assets
    image.png
index.html
...

With this knowledge, we can create a widget that handles the behavior for both mobile and web.
Note that we can use Image.network on web because the images are accessed through the network on web by default (that is how web works in general). The path would be yourdomain.com/assets/assets/image.png.

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';

class PlatformAwareAssetImage extends StatelessWidget {
  const PlatformAwareAssetImage({
    Key key,
    this.asset,
    this.package,
  }) : super(key: key);

  final String asset;
  final String package;

  @override
  Widget build(BuildContext context) {
    if (kIsWeb) {
      return Image.network(
        'assets/${package == null ? '' : 'packages/$package/'}$asset',
      );
    }

    return Image.asset(
      asset,
      package: package,
    );
  }
}

Potentially, this will be changed in future Flutter versions – this is the state of things as of v1.18.0-6.0.pre.82.

Answered By – creativecreatorormaybenot

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *