A flutter package to cache network image fastly without native dependencies.

Overview

Fast Cached Network Image

A flutter package to cache network image fastly without native dependencies, with loader, error builder, and smooth fade transitions. You can also add beautiful loaders and percentage indicators with the total and download size of the image.

MIT License pub dart

Screenshots

App caching

Caching with fade in animation

Caching with progress indicator and image  size

The below gif displays a 30 MB image from cache Use shimmer package to create a beautiful loading widget.

Usage

Depend on it

import 'package:fast_cached_network_image/fast_cached_network_image.dart';

Use path_provider to set a storage location for the db of images.

String storageLocation = (await getApplicationDocumentsDirectory()).path;

Initialize the cache configuration

await FastCachedImageConfig.init(path: storageLocation, clearCacheAfter: const Duration(days: 15));

The clearCacheAfter property is used to set the Duration after with the cached image will be cleared. By default its set to 7 days, which means an image cached today will be deleted when you open the app after 7 days.

Use it as a Widget

child: FastCachedImage(url: url)

Properties

errorBuilder: (context, exception, stacktrace) {
          return Text(stacktrace.toString());
        },

errorBuilder property needs to return a widget. This widget will be displayed if there is any error while loading the provided image.

loadingBuilder: (context, progress) {
                        return Container(
                          color: Colors.yellow,
                          child: Stack(
                            alignment: Alignment.center,
                            children: [
                              if (progress.isDownloading && progress.totalBytes != null)
                                Text('${progress.downloadedBytes ~/ 1024} / ${progress.totalBytes! ~/ 1024} kb',
                                    style: const TextStyle(color: Colors.red)),
                              SizedBox(
                                  width: 120,
                                  height: 120,
                                  child:
                                  CircularProgressIndicator(color: Colors.red, value: progress.progressPercentage.value)),
                            ],
                          ),
                        );
                      },

loadingBuilder property can be used to display a loading widget such as a shimmer. This widget will be displayed while the image is being downloaded and processed. loadingBuilder provides a progress property which can be used to display the image download progress with the size(in bytes) of the image.

fadeInDuration: const Duration(seconds: 1);

fadeInDuration property can be use to set the fadeInDuration between the loadingBuilder and the image. Default duration is 500 milliseconds

FastCachedImageConfig.isCached(imageUrl: url));

You can pass in a url to this method and check whether the image in the url is already cached.

FastCachedImageConfig.deleteCachedImage(imageUrl: url);

This method deletes the image with given url from cache.

FastCachedImageConfig.clearAllCachedImages();

This method removes all the cached images. This method can be used in situations such as user logout, where you need to clear all the images corresponding to the particular user.

If an image had some errors while displaying, the image will be automatically re - downloaded when the image is requested again.

FastCachedImage have all other default properties such as height, width etc. provided by flutter.

Example

import 'package:fast_cached_network_image/fast_cached_network_image.dart';
import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  String storageLocation = 'E:/fast';
  await FastCachedImageConfig.init(path: storageLocation, clearCacheAfter: const Duration(days: 15));

  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String url1 = 'https://www.sefram.com/images/products/photos/hi_res/7202.jpg';

  bool isImageCached = false;
  String? log;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SizedBox(
                    height: 150,
                    width: 150,
                    child: FastCachedImage(
                      url: url1,
                      fit: BoxFit.cover,
                      fadeInDuration: const Duration(seconds: 1),
                      errorBuilder: (context, exception, stacktrace) {
                        return Text(stacktrace.toString());
                      },
                      loadingBuilder: (context, progress) {
                        return Container(
                          color: Colors.yellow,
                          child: Stack(
                            alignment: Alignment.center,
                            children: [
                              if (progress.isDownloading && progress.totalBytes != null)
                                Text('${progress.downloadedBytes ~/ 1024} / ${progress.totalBytes! ~/ 1024} kb',
                                    style: const TextStyle(color: Colors.red)),
                              
                              SizedBox(
                                  width: 120,
                                  height: 120,
                                  child:
                                  CircularProgressIndicator(color: Colors.red, value: progress.progressPercentage.value)),
                            ],
                          ),
                        );
                      },
                    ),
                  ),

                  const SizedBox(height: 12),
                  
                  Text('Is image cached? = $isImageCached', style: const TextStyle(color: Colors.red)),
                 
                  const SizedBox(height: 12),
                  
                  Text(log ?? ''),

                  const SizedBox(height: 120),

                  MaterialButton(
                    onPressed: () async {
                      setState(() => isImageCached = FastCachedImageConfig.isCached(imageUrl: url1));
                    },
                    child: const Text('check image is cached or not'),
                  ),

                  const SizedBox(height: 12),

                  MaterialButton(
                    onPressed: () async {
                      await FastCachedImageConfig.deleteCachedImage(imageUrl: url1);
                      setState(() => log = 'deleted image $url1');
                      await Future.delayed(const Duration(seconds: 2), () => setState(() => log = null));
                    },
                    child: const Text('delete cached image'),
                  ),

                  const SizedBox(height: 12),

                  MaterialButton(
                    onPressed: () async {
                      await FastCachedImageConfig.clearAllCachedImages();
                      setState(() => log = 'All cached images deleted');
                      await Future.delayed(const Duration(seconds: 2), () => setState(() => log = null));
                    },
                    child: const Text('delete all cached images'),
                  ),
                ],
              ),
            )));
  }
}

Package on pub.dev

fast_cached_network_image

Comments
  • Stuck in loadingBuilder?

    Stuck in loadingBuilder?

    Thank you for sharing this great class! I have been using it on my app recently and it has worked fine most of the time.

    Sometimes when you lay the app in the background and take it into front, the loadingBuilder() is called and I uses a greybox and it is stuck dere. I have to force setState() to make it show the picture. Is this something you have observered?

    opened by large 6
  • Invalid Image Data

    Invalid Image Data

    Exception: Invalid image data - Image url : https://www.sefram.com/images/products/photos/hi_res/7202.jpg

    I am getting an issue where image is not being decoded. Is there any solutions to it

    Exception: Invalid image data - Image url : https://www.sefram.com/images/products/photos/hi_res/7202.jpg E/FlutterJNI(23406): Failed to decode image E/FlutterJNI(23406): android.graphics.ImageDecoder$DecodeException: Failed to create image decoder with message 'unimplemented'Input contained an error. E/FlutterJNI(23406): at android.graphics.ImageDecoder.nCreate(Native Method) E/FlutterJNI(23406): at android.graphics.ImageDecoder.access$200(ImageDecoder.java:173) E/FlutterJNI(23406): at android.graphics.ImageDecoder$ByteBufferSource.createImageDecoder(ImageDecoder.java:250) E/FlutterJNI(23406): at android.graphics.ImageDecoder.decodeBitmapImpl(ImageDecoder.java:1847) E/FlutterJNI(23406): at android.graphics.ImageDecoder.decodeBitmap(ImageDecoder.java:1840) E/FlutterJNI(23406): at io.flutter.embedding.engine.FlutterJNI.decodeImage(FlutterJNI.java:524) E/FlutterJNI(23406): Failed to decode image E/FlutterJNI(23406): android.graphics.ImageDecoder$DecodeException: Failed to create image decoder with message 'unimplemented'Input contained an error. E/FlutterJNI(23406): at android.graphics.ImageDecoder.nCreate(Native Method) E/FlutterJNI(23406): at android.graphics.ImageDecoder.access$200(ImageDecoder.java:173) E/FlutterJNI(23406): at android.graphics.ImageDecoder$ByteBufferSource.createImageDecoder(ImageDecoder.java:250) E/FlutterJNI(23406): at android.graphics.ImageDecoder.decodeBitmapImpl(ImageDecoder.java:1847) E/FlutterJNI(23406): at android.graphics.ImageDecoder.decodeBitmap(ImageDecoder.java:1840) E/FlutterJNI(23406): at io.flutter.embedding.engine.FlutterJNI.decodeImage(FlutterJNI.java:524)

    opened by Nabinda 1
  • Reload widget when change URL

    Reload widget when change URL

    Dear friend, when change the url the widget dont update the image.

    Observer( builder: (_) { return SizedBox( height: double.maxFinite, child: RotatedBox( quarterTurns: _rotate, child: FastCachedImage( url: premio.urlCanhoto, fit: BoxFit.fill, fadeInDuration: const Duration(seconds: 1), errorBuilder: (context, exception, stacktrace) { return Text(stacktrace.toString()); }, loadingBuilder: (context, progress) { return Container(); }, ), ), ); }, )

    How to change URL and update the widget?

    Thanks to advance

    question 
    opened by marcoprodata 4
  • Custom cache key

    Custom cache key

    This package looks promising and very simple. Ideally we can set a custom key, which is necessary if we work with more dynamic URLs like S3 signed URLs.

    question 
    opened by flodaniel 1
  • loadingBuilder required in package 1.0.1

    loadingBuilder required in package 1.0.1

    I have just upgraded to latest version and I had some issues. Images that did not use the loadingBuilder failed, with this error: flutter: Null check operator used on a null value - Image url : <link to image>

    After adding loadingBuilder: (c, p) { return Container(); } everything was back to normal. If these functions are an requirement, they should not be optional.

    opened by large 1
Owner
CHRISTO
Electronics & Communication Engineer, Flutter developer, Interested in Electronics & Microcontrollers
CHRISTO
A most easily usable cache management library in Dart. With CacheStorage, you can easily manage cache on your application.

A most easily usable cache management library in Dart! 1. About 1.1. Introduction 1.1.1. Install Library 1.1.2. Import It 1.1.3. Use CacheStorage 1.2.

Kato Shinya 1 Dec 13, 2021
Memory Cache is simple, fast and global in-memory cache with CRUD features.

Memory Cache Memory Cache is simple, fast and global in-memory cache. Features Create, read, update, delete and invalidate cache. Expirable Cache Gett

Gökberk Bardakçı 6 Dec 25, 2022
Dart package for Async Data Loading and Caching. Combine local (DB, cache) and network data simply and safely.

Stock is a dart package for loading data from both remote and local sources. It is inspired by the Store Kotlin library.

xmartlabs 59 Dec 24, 2022
how to Integrating facebook audience network to flutter app for banner, interstitial, rewarded, native and native banner

fb_ads_flutter_12 A new Flutter project. Getting Started Watch the complite tutorial for integrating Facebook ads into the Flutter app in our Youtube

null 4 Nov 26, 2022
Dart / Flutter package that allows discovering network devices in local network (LAN).

lan_scanner Dart / Flutter package that allows discovering network devices in local network (LAN). Note: This library is intended to be used on Class

null 12 Dec 9, 2022
A Dart/Flutter package to perform network calls. It uses Isolates to perform network calls on Dart VM environments and WebWorkers on Web.

ArDriveHTTP ArDriveHTTP is a package to perform network calls for ArDrive Web. It uses Isolates to perform network calls on Dart VM environments and W

AR.IO 2 Dec 15, 2022
Lite version of smart_select package, zero dependencies, an easy way to provide a single or multiple choice chips.

Lite version of smart_select package, zero dependencies, an easy way to provide a single or multiple choice chips. What's New in Version 2.x.x Added p

Irfan Vigma Taufik 97 Dec 15, 2022
A flutter package uses native implementations to resize an image

fast_image_resizer This package uses native implementations to resize an image.

Soeren Schoenbrod 0 Dec 20, 2021
Simple Dart package with build-in code generation. It simplifies and speedup creation of cache mechanism for dart classes.

Simple Dart package with build-in code generation. It simplifies and speedup creation of cache mechanism for dart classes.

iteo 37 Jan 2, 2023
A Flutter plugin that provides assets abstraction management APIs without UI integration, you can get assets (image/video/audio) on Android, iOS and macOS.

photo_manager Photo/Assets management APIs for Flutter without UI integration, you can get assets (image/video/audio) from Android, iOS and macOS. 提供相

FlutterCandies 526 Jan 4, 2023
Flutter starter project - boilerPlate for Clean Architecture with Domain-Driven-Design with commonly used dependencies

flutter_starter_project A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you

MJ Montes 0 Jan 2, 2022
Protofu is a Dart Command Line tool for generating your protobufs and included dependencies in one command.

ProtoFu - let me compile that for you ProtoFu exists to make working with protobufs easier. Gone are the days of downloading protoc and the dart proto

John McDole 5 Oct 27, 2022
Album Image is based in photo_manager package and has the same concept as image_picker but with a more attractive interface to choose an image or video from the device gallery, whether it is Android or iOS

Album Image is based in photo_manager package and has the same concept as image_picker but with a more attractive interface to choose an image or vide

Phuong Vu 2 Oct 13, 2022
Flutter native ads - Show AdMob Native Ads use PlatformView

flutter_native_ads Flutter plugin for AdMob Native Ads. Compatible with Android and iOS using PlatformView. Android iOS Getting Started Android Androi

sakebook 64 Dec 20, 2022
react-native native module for In App Purchase.

Documentation Published in website. Announcement Version 8.0.0 is currently in release candidate. The module is completely rewritten with Kotlin and S

dooboolab 2.3k Dec 31, 2022
dna, dart native access. A lightweight dart to native super channel plugin

dna, dart native access. A lightweight dart to native super channel plugin, You can use it to invoke any native code directly in contextual and chained dart code.

Assuner 14 Jul 11, 2022
A powerful plugin that fully uses the native image library's ability to display images on the flutter side.

PowerImage A powerful plugin that fully uses the native image library's ability to display images on the flutter side. 中文文档 Features: Supports the abi

Alibaba 422 Dec 23, 2022