Display asset images in Flutter

Images showing the implementation of this tutorial 1) Simple implementation with width argument. 2) Implementation of BoxFit.cover as value of fit argument. 3) Implementation of asset image as background of a container

Asset images are present in the asset bundle of the app. They are deployed with app and are readily available during run-time. Asset images can be displayed using the Image class in flutter.

Image class has constructors:

  1. Image.asset - To display image from assets bundle
  2. Image.file - To display image from a file
  3. Image.memory - To display image from Uint8List
  4. Image.network - To display image from a URL

Here in this tutorial, we use Image.asset to display an image from the assets bundle.

Simple Implementation

Step 1

The first step is to create a new folder and name it "assets" at the root of the Flutter project directory as shown in the image. Now add the image inside the newly created assets directory.

Step 2

The image added inside the assets folder won't be accessible until we list it in the assets section of our pubspec.yaml file. In step 2, list the image file under the assets section of pubspec.yaml as shown below

Step 3

Now everything is ready and we can do the coding to display our asset image.

This is a simple code snippet showing the implementation of Image.asset. Here we give the path to asset image and the width of the asset image to be displayed.

Fit Argument for Image

Instead of giving the width, you can fit the asset image inside a container with the fit argument. Here we use Boxfit.contain which makes the image contained inside the Container as shown in the image.

Image as the background of a Container

AssetImage Class can be used to display the asset image as the background of a container as shown in the example above.