Flutter Image.network is not showing when using loadingBuilder?

Viewed 1649

I'm using Image.network to load image from network. When I simply pass the url the image works fine. It will be displayed after few seconds. But when I use loadingBuilder and errorBuilder the images are loaded but not displayed. The circular progress I created inside the loadingBuilder completes and disappears but image is not shown.

Here code

Image.network(
      widget._imgLink,
      loadingBuilder: (context, child, loadingProgress) {
        return Center(
          child: CircularProgressIndicator(
            value: (loadingProgress != null)
                ? (loadingProgress.cumulativeBytesLoaded /
                    loadingProgress.expectedTotalBytes)
                : 0,
          ),
        );
      },
      errorBuilder: (context, error, stackTrace) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("Error loading"),
            FlatButton(onPressed: () {}, child: Text("Retry")),
          ],
        );
      },
    ),

How can I tell the widget to display the image after its loaded? Thank you.

2 Answers

Returning child from loadingBuilder when loadingProgress is null will work. Sample:

loadingBuilder: (context, child, loadingProgress) {
        if(loadingProgress == null)
          return child;

        return Center(
          child: CircularProgressIndicator(
            value: (loadingProgress != null)
                ? (loadingProgress.cumulativeBytesLoaded /
                    loadingProgress.expectedTotalBytes)
                : 0,
          ),
        );
      },

Use CachedNetworkImage which loads the image and provide error and loading widgets.

dependencies:
  cached_network_image: ^2.3.3

Code:

CachedNetworkImage(
  imageUrl: "http://via.placeholder.com/200x150",
  imageBuilder: (context, imageProvider) => Container(
    decoration: BoxDecoration(
      image: DecorationImage(
          image: imageProvider,
          fit: BoxFit.cover,
          colorFilter:
              ColorFilter.mode(Colors.red, BlendMode.colorBurn)),
    ),
  ),
  placeholder: (context, url) => CircularProgressIndicator(),
  errorWidget: (context, url, error) => Icon(Icons.error),
),
Related