FlutterImageWidgets

How to show placeholder while Network image is loading in Flutter

Placeholder images provide visual feedback to users that content is being loaded. Without placeholders, users might experience a blank space or delayed rendering, leading to a poorer user experience.

Users perceive the app as faster when they see immediate visual feedback, even if the actual image loading takes a moment. This perception of speed is crucial for retaining user engagement and satisfaction.

If users see a blank space instead of a placeholder, they might assume that the app is not working properly and leave the page (resulting in a higher bounce rate). A placeholder assures users that content is loading, encouraging them to wait for the complete page to load.

In this tutorial we will learn how to display placeholder while network image is being loaded in Flutter.

Show Placeholder image in Flutter

When we load a network image in flutter, it may take time to load fully image. So we have to show a placeholder image while the image is being loaded. To display this placeholder or default image we will place an image assets folder.  

Step 1: Add image in assets

Create an assets folder in project’s root directory. And put placeholder image in it.

Step 2: Include image in pubspec.yaml

Now open pubspec.yaml file and include this image in it like this.

flutter: 
  uses-material-design: true
  assets:
    - assets/placeholder.jpeg

After including, run this command

Flutter pub get

Step 3: Display placeholder image

FadeInImage widget allows us to display the placeholder image while the network image is loading. Let’s see how to use this.

FadeInImage(
  image: NetworkImage(imageUrl),
  placeholder: const AssetImage("assets/placeholder.jpeg"),
  fit: BoxFit.fitWidth,
)

This will show the default image from assets folder while the network image in being loaded.

Output

Placeholder in Flutter
Placeholder Image in Flutter

Handle Network Image Loading Error

Network image loading errors can occur due to various reasons such as a lack of internet connection, incorrect URL, server issues, or problems with the image file itself. Handling these errors is crucial to providing a smooth user experience.

Let’s see how to handle this issue in Flutter.

FadeInImage widget contains a imageErrorBuilder property. Its return type is widget. We can return any widget from this. This widget will be display if the network image fails to load due to any error.

FadeInImage(
  image: NetworkImage(imageUrl),
  placeholder: const AssetImage("assets/placeholder.jpeg"),
  fit: BoxFit.fitWidth,
  imageErrorBuilder:(context, error, stackTrace) {
    return Image.asset('assets/placeholder.jpeg',
        fit: BoxFit.fitWidth
    );
  },
)

Here we return the asset image if the network image fails to load.

Yow can also learn how to fit image in whole screen in Flutter

Leave a Reply

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