flutter assets logo

Flutter Basics – How to use an image in Flutter with examples

What is the Flutter Image widget?

The Flutter Image widget is a very useful tool for displaying images in your Flutter app. It is one of the basic building blocks of any Flutter app, and it is easy to use. To display an image in your app, you simply need to specify the image parameter of the Image widget with the location of the image file you want to display. For example:

Image(
  image: AssetImage('images/my_image.png'),
)

This will display the image file located at images/my_image.png in your Flutter app. You can also use other types of image sources, such as NetworkImage to display an image from the internet, or FileImage to display an image from the device’s local file system.

In addition to the image parameter, the Image widget also has a number of optional parameters that you can use to customize how the image is displayed. For example, you can use the height and width parameters to specify the dimensions of the image, and the fit parameter to control how the image is resized and positioned to fit those dimensions. For example:

Image(
  image: AssetImage('images/my_image.png'),
  height: 100,
  width: 200,
  fit: BoxFit.cover,
)

This code will display the image with a height of 100 and a width of 200. The image will be resized and positioned to cover the given dimensions while preserving the aspect ratio of the image. There are several other optional parameters available for the Image widget, such as color, alignment, and repeat, which can be used to further customize the appearance and behaviour of the image.

This is a result of simple research about how to use Images in Flutter. I am guessing this is a very big subject but I will try to use simple examples.

Add image to pubspec.yaml in Flutter

In Flutter, you can use images stored in the asset folder inside your app or images from the network.

Flutter uses the pubspec.yaml file, located at the root of your project, to identify assets required by an app.

To include an image in your Flutter app, you need to add it to the assets section of your pubspec.yaml file. Here is an example of how to do this:

assets:
  - images/my_image.png

This will include the image file located at images/my_image.png in the project’s asset folder. You can also include multiple image files by specifying a list of file paths:

assets:
  - images/my_image.png
  - images/my_image2.png
  - images/my_image3.png

Another example:

flutter:
  assets:
    - assets/my_icon.png
    - assets/FlutterAssets_logo_BG.jpg

To include all assets under a directory, specify the directory name with the / character at the end:

flutter:
  assets:
    - assets/
    - assets/subdirectory/

After adding the images to the pubspec.yaml file, you will need to run the flutter pub get command to update the project dependencies. Once the dependencies are updated, you will be able to use the AssetImage class to load the images in your Flutter code.

Image(
  image: AssetImage('images/my_image.png'),
)

This will display the image file located at images/my_image.png in your Flutter app.

Basic use of the Image.assets in Flutter

To use the Image.asset widget in Flutter, you need to include the desired image file in your Flutter project’s assets directory. Then, you can use the Image.asset widget to display the image in your app.

Here is an example of how to use the Image.asset widget:

Image.asset('images/my_image.png')

This will display the image file located at images/my_image.png in the project’s asset folder.

You can also specify the height and width of the image, and use the fit parameter to control how the image is resized and positioned to fit those dimensions.

Image.asset(
  'images/my_image.png',
  height: 100,
  width: 200,
  fit: BoxFit.cover,
)

This will display the image with a height of 100 and a width of 200. The image will be resized and positioned to cover the given dimensions while preserving the aspect ratio of the image.

There are many other optional parameters available for the Image.asset widget, such as color, alignment, and repeat, which can be used to further customize the appearance and behaviour of the image.

Here is another example:

            Container(
              height: 150,
              child: Image.asset('assets/FlutterAssets_logo_BG.jpg')
            ),

//or

          SizedBox(
              height: 150,
              child: Image.asset('assets/FlutterAssets_logo_BG.jpg')
            ),
image asset

How to use of Image.network in Flutter

To use the Image.network widget in Flutter, you need to provide the URL of the image you want to display. The Image.network widget will automatically download and display the image.

Here is an example of how to use the Image.network widget:

Image.network(
  'https://picsum.photos/250?image=9',
)

This will display the image located at the specified URL.

You can also specify the height and width of the image, and use the fit parameter to control how the image is resized and positioned to fit those dimensions.

Image.network(
  'https://picsum.photos/250?image=9',
  height: 100,
  width: 200,
  fit: BoxFit.cover,
)

This will display the image with a height of 100 and a width of 200. The image will be resized and positioned to cover the given dimensions while preserving the aspect ratio of the image.

There are many other optional parameters available for the Image.network widget, such as headers, cacheWidth, and errorBuilder, which can be used to customize the behaviour of the image.

In this example, I shortened the link to the image with TinyURL, but it still works. The effect is exactly as in above section.

Container(
                height: 150,
                child: Image.network('https://tinyurl.com/flutterassets')
            ),

//or

SizedBox(
                height: 150,
                child: Image.network('https://tinyurl.com/flutterassets')
            ),
image asset

Flutter Network Image with a placeholder

To load images from the network and use a placeholder you can use CachedNetworkImage.

CachedNetworkImage is a widget in the cached_network_image package for Flutter that allows you to display images from the internet and cache them for future use.

The CachedNetworkImage widget works by downloading the image from the specified URL and saving it in a cache on the device. When the image is needed again, the CachedNetworkImage widget will first check the cache to see if the image is available and display it from the cache if it is. If the image is not in the cache, the CachedNetworkImage widget will download it from the internet and display it.

To use it you have to add CachedNetworkImage to pubspec.yaml.

dependencies:
  flutter:
    sdk: flutter
  cached_network_image: ^3.2.0

In your dart file import the package.

import 'package:cached_network_image/cached_network_image.dart';

Use it in the desired place.

CachedNetworkImage(
                imageUrl: 'https://tinyurl.com/flutterassets',
                placeholder: (context, url) => CircularProgressIndicator(),
                errorWidget: (context, url, error) => Icon(Icons.error),
              ),

Flutter FadeInImage as a placeholder

To display a placeholder image while a network image is loading in Flutter, you can use the FadeInImage widget. The FadeInImage widget displays a placeholder image while the network image is loading, and then fades in the final image when it is ready.

Here is an example of how to use the FadeInImage widget:

              FadeInImage.assetNetwork(
                  placeholder: 'assets/FlutterAssets_logo.png',
                  image: 'https://tinyurl.com/flutterassets',
              ),

//or use gif image as placeholder

              FadeInImage.assetNetwork(
                  placeholder: 'assets/loading.gif',
                  image: 'https://tinyurl.com/flutterassets',
              ),

You can also specify the height and width of the image, and use the fit parameter to control how the image is resized and positioned to fit those dimensions.

FadeInImage(
  placeholder: AssetImage('assets/FlutterAssets_logo.png'),
  image: NetworkImage('https://tinyurl.com/flutterassets'),
  height: 100,
  width: 200,
  fit: BoxFit.cover,
)

This will display the placeholder image with a height of 100 and a width of 200, and then fade in the final image with the same dimensions. The image will be resized and positioned to cover the given dimensions while preserving the aspect ratio of the image.

How to stretch an image to fit the background in Flutter

To stretch an image to fit the background of a container in Flutter, you can use the BoxDecoration class with the fit: BoxFit.fill parameter.

Here is an example of how to stretch an image to fit the background of a container:

Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              width: MediaQuery.of(context).size.width,
              height: 100,
              decoration: BoxDecoration(
                image: DecorationImage(
                  fit: BoxFit.fill,
                  image: AssetImage('assets/FlutterAssets_logo_BG.jpg')
                ),
              ),
            ),Container(
              width: MediaQuery.of(context).size.width,
              height: 100,
              decoration: BoxDecoration(
                image: DecorationImage(
                  fit: BoxFit.cover,
                  image: AssetImage('assets/FlutterAssets_logo_BG.jpg')
                ),
              ),
            ),

          ],
        ),
image boxfit

How to use BoxFit in Flutter

BoxFit is an enum in Flutter that specifies how an image should be resized and positioned to fit a given box. It is often used in conjunction with the fit parameter of the Image widget.

Here is a list of the possible values for the BoxFit enum:

  • BoxFit.fill: The image is resized to fill the box, regardless of its aspect ratio. The image may be distorted in order to fill the box.
fit:BoxFit

  • BoxFit.contain: The image is resized to its largest size that fits within the box. The image will not be distorted, but there may be empty space within the box.
fit:BoxFit

  • BoxFit.cover: The image is resized to cover the entire box, preserving its aspect ratio. The image may extend outside the box, and some parts of the image may not be visible.
fit:BoxFit

  • BoxFit.fitHeight: The image is resized to fit the height of the box, preserving its aspect ratio. The width of the image may be smaller or larger than the box.
fit:BoxFit

  • BoxFit.fitWidth: The image is resized to fit the width of the box, preserving its aspect ratio. The height of the image may be smaller or larger than the box.
fit:BoxFit

  • BoxFit.none: The image is not resized. The image is positioned within the box according to the alignment parameter.
fit:BoxFit

  • BoxFit.scaleDown: The image is resized to its actual size or the largest size that fits within the box, whichever is smaller.
fit:BoxFit

Here is an example of how to use the BoxFit enum with the fit parameter of the Image widget:

Image(
  image: AssetImage('images/my_image.png'),
  fit: BoxFit.cover,
)

This will display the image and resize it to cover the entire box while preserving the aspect ratio of the image.

You can also specify the height and width of the image to control the size of the box.

Image(
  image: AssetImage('images/my_image.png'),
  height: 100,
  width: 200,
  fit: BoxFit.cover,
)

This will display the image with a height of 100 and a width of 200, and resize it to cover the given dimensions while preserving the aspect ratio of the image.

How to use Image box decoration in Flutter

To add a box decoration to an Image widget in Flutter, you can use the BoxDecoration class. The BoxDecoration class allows you to specify a background colour or image, as well as border and shadow properties for the box.

Here is an example of how to use the BoxDecoration class with an Image widget:



Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              margin: const EdgeInsets.all(10.0),
              width: MediaQuery.of(context).size.width,
              height: 150,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.red, width: 5.0,),
                shape: BoxShape.circle,
                boxShadow: [
                  BoxShadow(
                    color: Colors.red.withOpacity(0.5),
                    spreadRadius: 7,
                    blurRadius: 10,
                    offset: Offset(4, 4), // changes position of shadow
                  ),
                ],
                image: DecorationImage(
                    fit: BoxFit.fitHeight,
                    image: AssetImage('assets/FlutterAssets_logo_BG.jpg')
                ),
              ),
            ),

            Container(
              margin: const EdgeInsets.all(10.0),
              width: MediaQuery.of(context).size.width,
              height: 150,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.blue, width: 5.0,),
                borderRadius: BorderRadius.circular(20),
                boxShadow: [
                  BoxShadow(
                    color: Colors.blue.withOpacity(0.5),
                    spreadRadius: 7,
                    blurRadius: 10,
                    offset: Offset(4, 4), // changes position of shadow
                  ),
                ],
                image: DecorationImage(
                    fit: BoxFit.cover,
                    image: AssetImage('assets/FlutterAssets_logo_BG.jpg')
                ),
              ),
            ),

          ],
        ),

image boxdecoration 1

How to use Image inside Card in Flutter

To display an Image widget inside a Card widget in Flutter, you can simply wrap the Image widget in a Card widget and specify the desired Card properties.

Here is an example of how to use an Image widget inside a Card widget:

Card(
  elevation: 5,
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
  child: Image(
    image: AssetImage('images/my_image.png'),
  ),
)

This will display the image inside a card with an elevation of 5 and a border radius of 10.

You can also specify the height and width of the image, and use the fit parameter to control how the image is resized and positioned to fit those dimensions.

Card(
  elevation: 5,
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
  child: Image(
      image: AssetImage('images/my_image.png'),
      height: 100,
      width: 200,
    fit: BoxFit.cover,
  ),
),

This will display the image inside a card with an elevation of 5 and a border radius of 10. The image will be displayed with a height of 100 and a width of 200, and will be resized and positioned to cover the given dimensions while preserving the aspect ratio of the image.

You can also use the Card widget’s color and margin properties to further customize the appearance of the card.

Card(
  color: Colors.red,
  margin: EdgeInsets.all(20),
  elevation: 5,
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
  child: Image(
    image: AssetImage('images/my_image.png'),
    height: 100,
    width: 200,
    fit: BoxFit.cover,
  ),
)

This will display the image inside a red card with a margin of 20 around the entire card, an elevation of 5, and a border radius of 10. The image will be displayed with a height of 100 and a width of 200 and will be resized and positioned to cover the given dimensions while preserving the aspect ratio of the image.

Here is another example:

              SizedBox(
                width: MediaQuery.of(context).size.width,
                height: 100,
                child: Card(
                  semanticContainer: true,
                  clipBehavior: Clip.antiAliasWithSaveLayer,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  elevation: 10,
                  margin: EdgeInsets.symmetric(vertical: 5, horizontal: 20),
                  child: Container(
                    padding: const EdgeInsets.all(10.0),
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.black, width: 1.0,),
                      borderRadius: BorderRadius.circular(10),
                      image: DecorationImage(
                        image: AssetImage('assets/FlutterAssets_logo_BG.jpg'),
                        fit: BoxFit.fitWidth,
                      ),
                    ),
                    child: Text("YOUR TEXT", style: TextStyle(fontWeight: FontWeight.w900),),
                  ),
                ),
              ),
image in card