flutter_cached 4.2.1

When building an app that caches data, there are many special cases to think about.

For example, according to the Material Design guidelines, you need to worry about displaying offline data, handling swipe to refresh, showing error banners and displaying empty states.

This package aims to make implementing cached Flutter apps as easy as possible.

Usually, the frontend asks the backend to fetch data and the backend then offers a continuous Stream of data to your frontend. When listening to bare-bone streams in Dart, you usually have to work with AsyncSnapshots quite often.

This package offers a new, augmented type of communication path between backend and frontend designed around the providing of cached data.

+----------+                             +----+
| business +-----------------+  updates  | UI |
| logic    | CacheController |==========>|    |
|          |                 |<==========|    |
|          +-----------------+  fetch()  |    |
|          |                             |    |
|          +-----------------+  updates  |    |
|          | CacheController |==========>|    |
|          |                 |<==========|    |
|          +-----------------+  fetch()  |    |
+----------+                             +----+

The communication: CacheUpdate

This type provides not only data or an error (like a normal AsyncSnapshot), but also contains information about whether data is still being fetched. Also, every error is accompanied by a stack trace.

For comparison, here are the possible states of the AsyncSnapshot:

no datahas data
no errornothingwith data
has errorwith error-

Here are the possible states of a CacheUpdate:

no datahas data
fetchingno errorloadingcached
fetchinghas error--
not fetchingno errorinitialsuccess
not fetchinghas errorerrorerror but cache

Now that looks like an upgraded version of AsyncSnapshot!

The data layer #

CacheControllers glue together the logic for fetching data with the UI. You can call fetch on these controllers to fetch data. And you can call updates to get a stream of CacheUpdates.

There are currently two types of CacheControllers:

  • The SimpleCacheController accepts three functions: fetcher, saveToCacheand loadFromCache. When fetch is called, it simultaneously calls the fetcher and the loadFromCache function. If loadFromCache returns first, it sends out a CacheUpdate containing the cached data. When finally the fetcher returns, it sends out another CacheUpdate containing the actual data. It also passes the data to saveToCache.
  • The PaginatedCacheController is a CacheController specific to Lists of items. It works just like the SimpleCacheController except that the fetcher returns both a list of items as well as a PaginationState (this can be any class that implements isDone).
    Next to the fetch method, the PaginatedCacheController also has a fetchMore method, which calls the fetcher again, passing in the last state it returned.
    By saving the offset or a pagination token or something similar in the PaginationState, it's quite easy for clients to implement pagination.

Here's an example of how each of these controllers work:

// A simple controller asking the International Chuck Norris Database for
// jokes. The second fetch call causes a joke to be immediately printed.
// (Although this is not that great of an example, because the jokes are
// non-deterministic.)
final controller = SimpleCacheController<String>(
  fetcher: () async {
    final response = http.get('http://api.icndb.com/jokes/random/');
    return json.decode(response)['value']['joke'];
  saveToCache: (joke) async {
    await File('cache.txt').writeAsString(joke);
  loadFromCache: () async {
    return await File('cache.txt').readAsString();


await controller.fetch();
await controller.fetch();
class MyPaginationState implements PaginationState {
  MyPaginationState({this.offset, this.isDone});
  final int offset;
  final bool isDone;

// A paginated controller that requests an API with an increasing offset.
final controller = PaginatedCacheController<String, int>(
  fetcher: (state) async {
    final response = json.decode(http.get('…?offset=${state.offset}')).
    final items = response['items'].cast<String>().toList();

    return PaginationResponse(
      items: items,
      state: MyPaginationState(
        offset: state.offset + items.length,
        isDone: items.isEmpty,
  saveToCache: (data) => …;
  loadFromCache: () => …,


// Fetches data and some more data.
await controller.fetch();
await controller.fetchMore();
await controller.fetchMore();

// Re-fetches data. Displays the cached data as long as the Future is still
// loading.
await controller.fetch();
await controller.fetchMore();

The UI layer #

CachedRawBuilder #

Because parsing Stream<CacheUpdate<T>> is tedious, there's an equivalent to Flutter's built-in StreamBuilder that makes reacting to CacheUpdates easy:

  controller: controller,
  builder: (context, update) {
    return Container(color: update.hasData ? Colors.green : Colors.red);

CachedBuilder #

Often, CacheUpdates are handled similarly. The CachedBuilder provides several builder for special cases:

// The CachedBuilder supports pull-to-refresh out of the box.
  controller: controller,
  loadingScreenBuilder: (context) => …,
  // When an error occurs during fetching but there is cached data, the data is
  // still shown but an error banner is displayed at the top.
  errorBannerBuilder: (context, error, stackTrace) => …,
  // When there's no cached data and an errors occurs, it's shown in
  // full-screen.
  errorScreenBuilder: (context, error, stackTrace) => …,
  // There is data to show (either cached data or live data).
  builder: (context, data) {
      return Center(child: Text(data));

Note: By default, the CachedBuilder assumes that the builder returns a scrollable widget, like a ListView or GridView. If that's not the case, you need to set hasScrollBody to false in order for the swipe to refresh to work.

PaginatedListView #

Quite often, the cached data is a paginated list. This view takes care of loading more items.

And that's it! More description coming soon!

[4.2.1] - 2020-02-23

  • Add map method to CacheController.

[4.1.1] - 2020-02-13

  • Make CacheUpdate's (default) constructor public under the name .raw(…).

[4.1.0] - 2020-02-13

  • There are now several utility controllers: You can create a controller from a stream of controllers, a list of controllers as well as a list of CacheUpdates.

[4.0.0] - 2020-01-24

  • Refactored CacheController: There are now two concrete CacheController implementations: The SimpleCacheController and the PaginatedCacheController.
  • The CacheUpdate got several fancy constructors (initial, loading, cached, success, error) and getters (isNotFetching, hasNoData, hasNoError).
  • The readme got revised quite a bit.

[3.2.0] - 2020-01-24

  • Create CacheController interface and rename former CacheController to CacheControllerImpl.
  • Create PaginatedListView.

[3.1.0] - 2020-01-24

  • Add PaginatedCacheController.

[3.0.1] - 2019-11-09

  • Fix CacheController, where the data would be saved to the cache but not being sent directly to the updates streams.

[3.0.0] - 2019-11-02

  • When calling loadFromCache, the CacheController only catches NotInCacheExceptions, not all possible errors. That makes it simpler to debug, because you need to explicitly throw this error if the cache is empty. Other errors will still bubble up to the debugger.
  • The CacheUpdate now also contains a stackTrace if it contains an error. That makes debugging even easier.

[2.1.1] - 2019-11-02

  • You don't need to call dispose anymore. If you want to listen to multiple update streams of the same controller, just request updates multiple times.

[2.1.0] - 2019-11-02

  • Optionally provide a controllerBuilder instead of a controller to the CachedRawBuilder or the CachedBuilder. dispose is called automatically.

[2.0.2] - 2019-10-14

  • Provide lastData and lastError getters on CacheController.

[2.0.1] - 2019-10-12

  • Update examples.
  • Complete transition to flutter_cached.
  • Remove list_diff dependency.

[2.0.0] - 2019-10-12

  • Complete overhaul of the API.
  • Package moved to flutter_cached.

[1.1.5] - 2019-10-11

  • Add more examples to the demo. Now all abstraction levels are covered.
  • Fix unbound vertical height issue caused by AnimatedCrossFade.

[1.1.4] - 2019-10-11

  • Fix type propagation on CacheController's updates.

[1.1.3] - 2019-10-06

  • We now depend on the pull_to_refresh package so that we can start the refresh indicator programatically.
  • Fix missing meta dependency.

[1.1.2] - 2019-10-05

  • CachedListView now takes either an itemBuilder for building the items directly one after another in an index-agnostic deterministic way or it takes an itemSliverBuilder for transforming all the items into slivers simultaneously, allowing for changing the order, grouping etc of items.

[1.1.1] - 2019-10-04

  • Fix type propagation for CachedCustomScrollView.

[1.1.0] - 2019-10-04

  • Add abstraction level below CachedListView: CachedCustomScrollView.
  • Rename CacheManager to CacheController.
  • Update readme to reflect changes and display screenshots in table.

[1.0.0] - 2019-10-04

  • Add CacheManager and CachedListView.


example #

A new Flutter project.

Getting Started #

This project is a starting point for a Flutter application.

A few resources to get you started if this is your first Flutter project:

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

Use this package as a library

1. Depend on it

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

  flutter_cached: ^4.2.1

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:flutter_cached/flutter_cached.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

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

  • Dart: 2.7.1
  • pana: 0.13.5
  • Flutter: 1.12.13+hotfix.7


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.2 <3.0.0
flutter 0.0.0
meta ^1.1.7 1.1.8
pull_to_refresh ^1.5.6 1.5.8
Transitive dependencies
collection 1.14.11 1.14.12
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies