Flutter Cache Network Image and Lazy Loading With Image Placeholder

Created At: 2022-05-10 07:33:36 Updated At: 2023-09-13 04:34:31

CachedNetworkImage shows a network image using a caching mechanism. It also provides support for a placeholder, showing an error and fading into the loaded image.  Next to that it supports most features of a default Image widget.

This could also work as solution for saving bandwith. And a lot of time android emulator does not load large image from network. It may keep showing connection closed. The solution could be using network image using caching mechanism. So there is where this plugin shines.

We will use a plugin called

cached_network_image

Get the complete code for this

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
  runApp(
      MaterialApp(
        home: MyApp(),
      )
  );
}

class MyApp extends StatefulWidget{
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title:const Text("Caching and Lazy Loading Images"),
          backgroundColor: Colors.redAccent,
        ),
        body: Container(
            padding: const EdgeInsets.all(20),
            child:Column(
                children: <Widget>[
                  CachedNetworkImage(
                    imageUrl: "http://mvs.bslmeiyu.com/storage/profile/2022-05-02-626fc39bf18a6.png",
                    imageBuilder: (context, imageProvider) => Container(
                      width: 400,
                      height: 200,
                      decoration: BoxDecoration(
                        image: DecorationImage( //image size fill
                          image: imageProvider,
                          fit: BoxFit.fitWidth,
                        ),
                      ),
                    ),
                    placeholder: (context, url) => Container(
                      alignment: Alignment.center,
                      child: CircularProgressIndicator(), // you can add pre loader iamge as well to show loading.
                    ), //show progress  while loading image
                    errorWidget: (context, url, error) => Image.asset("images/flutter.png"),
                    //show no image available image on error loading
                  ),
                 //show progress  while loading image

                ]
            )
        )
    );
  }
}

You may replace the placeholder child with an image from the assets folder or using CircularProgressIndicator()

You can play some of the properties or fileds of this plugin.

If you don't want to use cached_network_image, there is an alternative to this. This is called FadeInImage widget

Comment

Add Reviews