cached_listview 2.0.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 80

This package is no longer maintained, because it has been moved to a new location: flutter_cached

Original documentation:

When building a screen that displays a cached list of items, there are many special cases to think about.

For example, on material.io there are guidelines on how to handle displaying offline data, how pull-to-refresh should be implemented and when to use error banners or empty states.

This package tries to make implementing cached ListViews as easy as possible.

loading with no data in cacheloading with data in cacheloading successful
error with no data in cacheerror with data in cacheno data available

Usage #

First, create a CacheController. This will be the class that orchestrates the fetching of data.

var cacheController = CacheController<Item>(
  // Does the actual work and returns a Future<List<Item>>.
  fetcher: _downloadData,
  // Asynchronously saves a List<Item> to the cache.
  saveToCache: _saveToCache,
  // Asynchronously loads a List<Item> from the cache.
  loadFromCache: _loadFromCache,
);

Then you can create a CachedListView in your widget tree:

CachedListView(
  controller: cacheController,
  itemBuilder: (context, item) => ...,
  errorBannerBuilder: (context, error) => ...,
  errorScreenBuilder: (context, error) => ...,
  emptyStateBuilder: (context) => ...,
),

CachedRawBuilder

CachedRawCustomScrollView

CachedCustomScrollView

CachedListView

[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/lib/main.dart

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:cached_listview/cached_listview.dart';
import 'package:list_diff/list_diff.dart';

import 'cached_raw_builder.dart';
import 'cached_builder.dart';

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

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

class _MyAppState extends State<MyApp> {
  List<int> inMemoryCache;
  CacheController<List<int>> controller;

  @override
  void initState() {
    super.initState();

    var random = Random();
    controller = CacheController<List<int>>(
      // The fetcher just waits and then either crashes or returns a list of
      // random numbers.
      fetcher: () async {
        await Future.delayed(Duration(seconds: 2));
        if (random.nextDouble() < 0.8) {
          return List.generate(random.nextInt(100), (i) => random.nextInt(10));
        }
        if (random.nextDouble() < 0.1) {
          return [];
        }
        throw UnsupportedError('Oh no! Something terrible happened.');
      },
      loadFromCache: () async {
        if (inMemoryCache == null) {
          throw StateError('Nothing saved in cache.');
        }
        return inMemoryCache;
      },
      saveToCache: (data) async => inMemoryCache = data,
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Cached ListView examples')),
        body: Builder(
          builder: (context) {
            return ListView(
              children: <Widget>[
                ListTile(
                  title: Text('CachedBuilder demo'),
                  onTap: () => Navigator.of(context).push(MaterialPageRoute(
                    builder: (_) => CachedBuilderDemo(
                      controller: controller,
                    ),
                  )),
                ),
                ListTile(
                  title: Text('CachedRawBuilder demo'),
                  onTap: () => Navigator.of(context).push(MaterialPageRoute(
                    builder: (_) => CachedRawBuilderDemo(
                      controller: controller,
                    ),
                  )),
                ),
                ListTile(
                  title: Text('Example demo'),
                  onTap: () => Navigator.of(context).push(MaterialPageRoute(
                    builder: (_) => ExampleDemo(),
                  )),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}

class ExampleDemo extends StatefulWidget {
  @override
  _ExampleDemoState createState() => _ExampleDemoState();
}

class _ExampleDemoState extends State<ExampleDemo> {
  final _listKey = GlobalKey<AnimatedListState>();
  List<int> data = [1, 2, 3];

  var sizeTween = Tween<double>(begin: 0, end: 1);

  void initState() {
    super.initState();
  }

  Future<void> setData() async {
    final random = Random();
    final operations =
        await diff(data, List.generate(10, (_) => random.nextInt(10)));
    setState(() {
      for (var operation in operations) {
        operation.applyTo(data);
        if (operation.isInsertion) {
          _listKey.currentState.insertItem(operation.index);
        } else if (operation.isDeletion) {
          _listKey.currentState.removeItem(operation.index,
              (context, animation) {
            return SizeTransition(
              sizeFactor: animation.drive(sizeTween),
              child: ListTile(title: Text('${operation.item}')),
            );
          });
        }
      }
    });
    print(data);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Numbers')),
      body: RefreshIndicator(
        onRefresh: setData,
        child: AnimatedList(
          key: _listKey,
          initialItemCount: 3,
          itemBuilder: (context, index, animation) {
            return SizeTransition(
              sizeFactor: animation.drive(sizeTween),
              child: ListTile(title: Text('${data[index]}')),
            );
          },
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  cached_listview: ^2.0.0

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

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

  • Dart: 2.8.4
  • pana: 0.13.13
  • Flutter: 1.17.5

Analysis suggestions

Package not compatible with SDK dart

because of import path [cached_listview] that is in a package requiring null.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.2 <3.0.0
flutter 0.0.0
list_diff ^1.1.1 1.3.0
meta ^1.1.7 1.1.8
pull_to_refresh ^1.5.6 1.6.0
Transitive dependencies
async 2.4.1
collection 1.14.12 1.14.13
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8
Dev dependencies
flutter_test