cached_network_image 2.3.0-beta

  • Readme
  • Changelog
  • Example
  • Installing
  • 99

Cached network image #

Widget now uses builders for the placeholder and error widget and uses sqflite for cache management. See the docs for more information.

pub package

A flutter library to show images from the internet and keep them in the cache directory.

How to use #

The CachedNetworkImage can be used directly or through the ImageProvider. The ImageProvider has very minimal support for web. It currently doesn't include caching.

With a placeholder:

CachedNetworkImage(
        imageUrl: "http://via.placeholder.com/350x150",
        placeholder: (context, url) => CircularProgressIndicator(),
        errorWidget: (context, url, error) => Icon(Icons.error),
     ),

Or with a progress indicator:

CachedNetworkImage(
        imageUrl: "http://via.placeholder.com/350x150",
        progressIndicatorBuilder: (context, url, downloadProgress) => 
                CircularProgressIndicator(value: downloadProgress.progress),
        errorWidget: (context, url, error) => Icon(Icons.error),
     ),
Image(image: CachedNetworkImageProvider(url))

When you want to have both the placeholder functionality and want to get the imageprovider to use in another widget you can provide an imageBuilder:

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),
),

How it works #

The cached network images stores and retrieves files using the flutter_cache_manager.

[2.3.0-beta] - 2020-05-20 #

  • Rewrote image widget by using OctoImage.

[2.2.0+1] - 2020-05-05 #

  • Fix ImageProvider not using provided headers.

[2.2.0] - 2020-04-30 #

  • Upgrades on CachedNetworkImageProvider:
    • Support for download progress.
    • Basic web support (no caching).

[2.1.0+1] - 2020-04-10 #

  • Update minimal Dart sdk version

[2.1.0] - 2020-04-10 #

  • Update CacheManager
  • Added option for progress indicator

[2.0.0] - 2019-12-31 #

  • Public release of 2.0 version

[2.0.0-rc.1] - 2019-11-04 #

  • Revert scaling of image due to issues with BoxFit.

[2.0.0-rc] - 2019-10-17 #

[1.1.3] - 2019-11-04 #

  • Revert scaling of image due to issues with BoxFit.

[1.1.2+1] - 2019-10-17 #

  • Fix for widgets declared with infinite size.

[1.1.2] - 2019-10-16 #

  • Add filterQuality property.
  • Scale image to size when showing in widget.
  • Better error handling.
  • Fix for useOldImageOnUrlChange.
  • Update cache manager to 1.1.2.

[1.1.1] - 2019-07-23 #

  • Updated cache manager for error handling fix

[1.1.0] - 2019-07-13 #

  • Improved performance
  • Keep fetched files in sync with filemanager.
  • Better error handling.
  • Added extra example to show the imageBuilder

[1.0.0] - 2019-06-27 #

  • Updated dependencies

[0.8.0] - 2019-05-06 #

  • Fixed compile error on informationCollector by temporarily disabling it.

[0.7.0] - 2019-03-06 #

  • BREAKING CHANGE: Renamed ErrorWidgetBuilder to LoadingErrorWidgetBuilder
  • LoadingErrorWidgetBuilder returns an Object instead of an Exception
  • Fixed BoxFit to also work when size is not defined

[0.6.2] - 2019-02-27 #

  • Added option to blend image with color
  • Added option in CacheManager to clear the cache

[0.6.1] - 2019-02-25 BREAKING CHANGES #

  • No longer assume infinite size.

[0.6.0] - 2019-02-18 BREAKING CHANGES #

  • Breaking changes in API and behaviour
  • Very much improved though
  • Adapted for new cache manager library
  • Completely rewritten image view
  • Now using builders for placeholder and error widgets
  • Added optional builder to customize the image

[0.5.1] - 2018-11-19 #

  • Fixed error throwing

[0.5.0] - 2018-10-13 #

  • Updated cache manager for http 0.12.0

[0.4.2] - 2018-08-30 #

  • Updated cache manager dependency

[0.4.1] - 2018-04-27 #

  • Improved error handling when a file could not be loaded.

[0.4.0] - 2018-04-14 #

  • Added optional headers.
  • Changed to Dart 2.0
  • Fixed bug when updating widget with new url

[0.3.0] - 2018-02-09 #

  • Added CachedNetworkImage with placeholder and error widgets.

[0.2.1] - 2018-01-08 #

  • Moved from OneFrameImageStreamCompleter to MultiFrameImageStreamCompleter.
  • Updated CacheManager dependency for critical bug fix.

[0.2.0] - 2017-12-29 #

  • Breaking change Removed CachedNetworkImage. From now on only the ImageProvider is supported. For a placeholder use FadeInImage. See also "Fallback for Network Images".
  • Moved CacheManager to a separate library for a more generic purpose.

[0.1.0] - 2017-12-21 #

  • Breaking change. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version. Instructions can be found here.

[0.0.2] - 10 December 2017 #

Added an ImageProvider and improved documentation

[0.0.1] - 2 December 2017 #

Initial release, should be polished

example/lib/main.dart

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blurhash/flutter_blurhash.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'CachedNetworkImage Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int currentPage = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('CachedNetworkImage')),
      body: _content(currentPage),
      bottomNavigationBar: BottomNavigationBar(
        onTap: (value) => setState(() {
          currentPage = value;
        }),
        currentIndex: currentPage,
        items: [
          const BottomNavigationBarItem(
            icon: Icon(Icons.image),
            title: Text('Basic'),
          ),
          const BottomNavigationBarItem(
            icon: Icon(Icons.list),
            title: Text('ListView'),
          ),
          const BottomNavigationBarItem(
            icon: Icon(Icons.grid_on),
            title: Text('GridView'),
          ),
        ],
      ),
    );
  }

  Widget _content(int page) {
    switch (currentPage) {
      case 0:
        return _basicContent();
      case 1:
        return _listViewContent();
      case 2:
        return _gridView();
      default:
        return _basicContent();
    }
  }

  Widget _basicContent() {
    return SingleChildScrollView(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _blurHashImage(),
            _sizedContainer(
              const Image(
                image: CachedNetworkImageProvider(
                  'http://via.placeholder.com/350x150',
                ),
              ),
            ),
            _sizedContainer(
              CachedNetworkImage(
                progressIndicatorBuilder: (context, url, progress) =>
                    CircularProgressIndicator(
                  value: progress.progress,
                ),
                imageUrl:
                    'https://images.unsplash.com/photo-1532264523420-881a47db012d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9',
              ),
            ),
            _sizedContainer(
              CachedNetworkImage(
                placeholder: (context, url) =>
                    const CircularProgressIndicator(),
                imageUrl: 'http://via.placeholder.com/200x150',
              ),
            ),
            _sizedContainer(
              CachedNetworkImage(
                imageUrl: 'http://via.placeholder.com/300x150',
                imageBuilder: (context, imageProvider) => Container(
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: imageProvider,
                      fit: BoxFit.cover,
                      colorFilter: const ColorFilter.mode(
                        Colors.red,
                        BlendMode.colorBurn,
                      ),
                    ),
                  ),
                ),
                placeholder: (context, url) =>
                    const CircularProgressIndicator(),
                errorWidget: (context, url, error) => const Icon(Icons.error),
              ),
            ),
            CachedNetworkImage(
              imageUrl: 'http://via.placeholder.com/300x300',
              placeholder: (context, url) => const CircleAvatar(
                backgroundColor: Colors.amber,
                radius: 150,
              ),
              imageBuilder: (context, image) => CircleAvatar(
                backgroundImage: image,
                radius: 150,
              ),
            ),
            _sizedContainer(
              CachedNetworkImage(
                imageUrl: 'http://notAvalid.uri',
                placeholder: (context, url) =>
                    const CircularProgressIndicator(),
                errorWidget: (context, url, error) => const Icon(Icons.error),
              ),
            ),
            _sizedContainer(
              CachedNetworkImage(
                imageUrl: 'not a uri at all',
                placeholder: (context, url) =>
                    const CircularProgressIndicator(),
                errorWidget: (context, url, error) => const Icon(Icons.error),
              ),
            ),
            _sizedContainer(
              CachedNetworkImage(
                imageUrl: 'http://via.placeholder.com/350x200',
                placeholder: (context, url) =>
                    const CircularProgressIndicator(),
                errorWidget: (context, url, error) => const Icon(Icons.error),
                fadeOutDuration: const Duration(seconds: 1),
                fadeInDuration: const Duration(seconds: 3),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _blurHashImage() {
    return SizedBox(
      width: double.infinity,
      child: CachedNetworkImage(
        placeholder: (context, url) => const AspectRatio(
          aspectRatio: 1.6,
          child: BlurHash(hash: 'LEHV6nWB2yk8pyo0adR*.7kCMdnj'),
        ),
        imageUrl: 'https://blurha.sh/assets/images/img1.jpg',
        fit: BoxFit.cover,
      ),
    );
  }

  Widget _listViewContent() {
    return ListView.builder(
      itemBuilder: (BuildContext context, int index) => Card(
        child: Column(
          children: <Widget>[
            CachedNetworkImage(
              imageUrl: 'https://loremflickr.com/320/240/music?lock=$index',
              placeholder: (BuildContext context, String url) => Container(
                width: 320,
                height: 240,
                color: Colors.purple,
              ),
            ),
          ],
        ),
      ),
      itemCount: 250,
    );
  }

  Widget _gridView() {
    return GridView.builder(
      itemCount: 250,
      gridDelegate:
          const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
      itemBuilder: (BuildContext context, int index) => CachedNetworkImage(
        imageUrl: 'https://loremflickr.com/100/100/music?lock=$index',
        placeholder: _loader,
        errorWidget: _error,
      ),
    );
  }

  Widget _loader(BuildContext context, String url) {
    return const Center(
      child: CircularProgressIndicator(),
    );
  }

  Widget _error(BuildContext context, String url, dynamic error) {
    print(error);
    return const Center(child: Icon(Icons.error));
  }

  Widget _sizedContainer(Widget child) {
    return SizedBox(
      width: 300.0,
      height: 150.0,
      child: Center(child: child),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  cached_network_image: ^2.3.0-beta

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:cached_network_image/cached_network_image.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
100
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
95
Overall:
Weighted score of the above. [more]
99
Learn more about scoring.

We analyzed this package on May 20, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.1
  • pana: 0.13.8-dev
  • Flutter: 1.17.0

Maintenance suggestions

Package is pre-release. (-5 points)

Pre-release versions should be used with caution; their API can change in breaking ways.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
flutter_cache_manager ^1.2.0 1.2.2
octo_image ^0.1.0 0.1.0
Transitive dependencies
charcode 1.1.3
clock 1.0.1
collection 1.14.12
convert 2.1.1
crypto 2.1.4
file 5.1.0
flutter_blurhash 0.4.2 0.5.0
http 0.12.1
http_parser 3.1.4
intl 0.16.1
meta 1.1.8
path 1.7.0
path_provider 1.6.8
path_provider_macos 0.0.4+2
path_provider_platform_interface 1.0.2
platform 2.2.1
plugin_platform_interface 1.0.2
rxdart 0.24.1
sky_engine 0.0.99
source_span 1.7.0
sqflite 1.3.0+1
sqflite_common 1.0.1
string_scanner 1.0.5
synchronized 2.2.0
term_glyph 1.1.0
transparent_image 1.0.0
typed_data 1.1.6
uuid 2.0.4
vector_math 2.0.8
Dev dependencies
flutter_test
mockito ^4.1.1
pedantic ^1.8.0+1 1.9.0