Generic cache manager for flutter

Overview

flutter_cache_manager

pub package Build Status codecov

A CacheManager to download and cache files in the cache directory of the app. Various settings on how long to keep a file can be changed.

It uses the cache-control http header to efficiently retrieve files.

The more basic usage is explained here. See the complete docs for more info.

Usage

The cache manager can be used to get a file on various ways The easiest way to get a single file is call .getSingleFile.

    var file = await DefaultCacheManager().getSingleFile(url);

getFileStream(url) returns a stream with the first result being the cached file and later optionally the downloaded file.

getFileStream(url, withProgress: true) when you set withProgress on true, this stream will also emit DownloadProgress when the file is not found in the cache.

downloadFile(url) directly downloads from the web.

getFileFromCache only retrieves from cache and returns no file when the file is not in the cache.

putFile gives the option to put a new file into the cache without downloading it.

removeFile removes a file from the cache.

emptyCache removes all files from the cache.

Custom Cache Key

By default the cache uses the url as the cache key. However, a custom cache key can be specified instead, meaning that files requested by url can be accessed from the cache using key. This is useful for scenarios where the URL for a resource can change, but the resource itself stays the same. Some examples include:

  1. Files stored in Firebase, where getDownloadURL can return a different URL for the same file

  2. Using pre-signed URLs from services such as AWS S3 or CloudFront, where the expiration time is embedded in the URL and causes the URLs to change over time.

To specify a custom key, use the optional key parameter when getting the file:

final file = await cacheManager.getSingleFile(
  'http://example.com/resource',
  key: 'MySpecialCacheKey',
)

The custom key must be used for each subsequent access to the file in order for the cached version to be used.

Using a custom key would typically be used when accessing a resource by ID (eg using a record from a database)

final file = await cacheManager.getSingleFile(
  resource.getDownloadURL(),
  key: resource.id
);

Settings

The cache manager is customizable by extending the BaseCacheManager. Below is an example with other settings for the maximum age of files, maximum number of objects and a custom FileService. The key parameter in the constructor and the getFilePath method are mandatory.


class CustomCacheManager extends BaseCacheManager {
  static const key = "customCache";

  static CustomCacheManager _instance;

  factory CustomCacheManager() {
    if (_instance == null) {
      _instance = new CustomCacheManager._();
    }
    return _instance;
  }

  CustomCacheManager._() : super(key,
      maxAgeCacheObject: Duration(days: 7),
      maxNrOfCacheObjects: 20);

  Future<String> getFilePath() async {
    var directory = await getTemporaryDirectory();
    return p.join(directory.path, key);
  }
}

If the file is located on Firebase Storage it can be accessed by using the provided FirebaseHttpFileService. Wherever the url is provided now becomes a Firebase Storage path, e.g. getFileStream(firebaseStoragePath).


class FirebaseCacheManager extends BaseCacheManager {
  static const key = 'firebaseCache';

  static FirebaseCacheManager _instance;

  factory FirebaseCacheManager() {
    _instance ??= FirebaseCacheManager._();
    return _instance;
  }

  FirebaseCacheManager._() : super(key, fileService: FirebaseHttpFileService());

  @override
  Future<String> getFilePath() async {
    var directory = await getTemporaryDirectory();
    return p.join(directory.path, key);
  }
}

How it works

By default the cached files are stored in the temporary directory of the app. This means the OS can delete the files any time.

Information about the files is stored in a database using sqflite. The file name of the database is the key of the cacheManager, that's why that has to be unique.

This cache information contains the end date till when the file is valid and the eTag to use with the http cache-control.

You might also like...

A flutter plugin which provides Crop Widget for cropping images.

A flutter plugin which provides Crop Widget for cropping images.

A flutter plugin which provides Crop Widget for cropping images. crop_your_image provides only minimum UI for deciding cropping area inside images. Other UI parts, such as "Crop" button or "Change Aspect Ratio" button, need to be prepared by each app developers.

Dec 31, 2022

Image caching system for flutter

image_cacheing image_cacheing is an image caching package. It is currently tested for Android applications. ImageCacheing widget takes url as a param.

May 31, 2021

A simple and easy flutter demo to crop image

flutter_image_crop A simple demo to crop image on flutter easily. A Chinese version of this document can be found here Flutter_image_crop Plugin will

Jul 8, 2021

A flutter package which makes it easy to track a series of images.

A flutter package which makes it easy to track a series of images.

A flutter package which makes it easy to track a series of images.

Oct 7, 2022

A flutter tool to generate beautiful code snippets in the form of an image.

A flutter tool to generate beautiful code snippets in the form of an image.

A flutter tool to generate beautiful code snippets in the form of an image.

Jan 18, 2022

A OpenGLES context canvas in flutter.

gl_canvas A OpenGLES context canvas in flutter. Usage // New a GLCanvas require a builder GLCanvas( builder: _builder, ) The builder should return

Oct 17, 2022

Simple and effective cross platform image saver for flutter, supported web and desktop

Simple and effective cross platform image saver for flutter, supported web and desktop

Oct 5, 2022

The iMateral Pro Icon pack available as Flutter Icons

The iMateral Pro Icon pack available as Flutter Icons

imaterial_pro_flutter This flutter package allows you to use the IMaterial Pro Icons. 🎖 Installation In the dependencies: section of your pubspec.yam

Oct 5, 2022

a package for flutter canvas paint dash line path easily.

a package for flutter canvas paint dash line path easily.

dash_painter a package for flutter canvas paint dash line path easily. 1. DashPainter 如何使用 DashPainter 只负责对 路径 Path 的虚线化绘制,不承担组件职能。 一般用在拥有 Canvas 对象的回

Oct 9, 2022
Comments
  • Update cache_object_provider.dart

    Update cache_object_provider.dart

    Transactional lock, when having too many images dowloaded at 1 time, I am sharing this fix to you, hopefully this will solve download errors

    :sparkles: What kind of change does this PR introduce? (Bug fix, feature, docs update...)

    The PR uses transactions for all database mutable oprations

    :arrow_heading_down: What is the current behavior?

    currently its directly updating to db which causes DB lock when too many images are downloaded to cache

    :new: What is the new behavior (if this is a feature change)?

    to any database mutable operations, it uses transactions now

    :boom: Does this PR introduce a breaking change?

    no, as far as I know

    :bug: Recommendations for testing

    test it with very large image list

    :memo: Links to relevant issues/docs

    :thinking: Checklist before submitting

    • [ ] All projects build
    • [ ] Follows style guide lines (code style guide)
    • [ ] Relevant documentation was updated
    • [ ] Rebased onto current develop
    opened by poldz 0
A powerful official extension library of image, which support placeholder(loading)/ failed state, cache network, zoom pan image, photo view, slide out page, editor(crop,rotate,flip), paint custom etc.

extended_image Language: English| 中文简体 A powerful official extension library of image, which support placeholder(loading)/ failed state, cache network

FlutterCandies 1.6k Dec 31, 2022
A simple Flutter Package to Mimic iMessage Image Picker for Flutter

A simple Flutter Package to Mimic iMessage Image Picker for Flutter

Paras Jain 64 Dec 26, 2022
A flutter carousel widget, support infinite scroll, and custom child widget.

carousel_slider A carousel slider widget. Features Infinite scroll Custom child widgets Auto play Supported platforms Flutter Android Flutter iOS Flut

serenader 1.4k Dec 30, 2022
A Flutter widget that paints an image and moves it at a slower speed than the main scrolling content.

A Flutter widget that paints an image and moves it at a slower speed than the main scrolling content. Installation Add dependency to your pubspec.yaml

Anatoly Pulyaevskiy 272 Dec 23, 2022
📸 Easy to use yet very customizable zoomable image widget for Flutter, Photo View provides a gesture sensitive zoomable widget. Photo View is largely used to show interacive images and other stuff such as SVG.

Flutter Photo View A simple zoomable image/content widget for Flutter. PhotoView enables images to become able to zoom and pan with user gestures such

Fire Slime Games 1.7k Jan 3, 2023
SVG parsing, rendering, and widget library for Flutter

flutter_svg Draw SVG (and some Android VectorDrawable (XML)) files on a Flutter Widget. Getting Started This is a Dart-native rendering library. Issue

Dan Field 1.5k Jan 6, 2023
A Flutter plugin for Android and iOS supports cropping images

Image Cropper A Flutter plugin for Android and iOS supports cropping images. This plugin is based on two different native libraries so it comes with d

HungHD 891 Dec 28, 2022
Flutter plugin that allows you to display multi image picker on iOS and Android. 👌🔝🎉

IMPORTANT: This repository has been archived and no longer mantained. As I don't have time anymore to work on the package it became very outdated. For

Radoslav Vitanov 898 Apr 29, 2021
Use lottie in flutter for both iOS and Android

flutter_lottie Use Lottie in Flutter. Supports both iOS and Android using lottie-ios and lottie-android Current Status Supports most features that bot

Cameron Smith 160 Nov 25, 2022
A Flutter package for manipulating bitmaps

Flutter Bitmap A minimalist Flutter package to perform fast bitmaps operations. The focus here is to provide a cool bitmap manipulation interface. The

Renan 152 Dec 23, 2022