firestore_cache 0.1.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 81

Firestore Cache #

A Flutter plugin for fetching Firestore documents with read from cache first then server.

pub package MIT License

This plugin is mainly designed for applications using the DocumentReference.get() and Query.getDocuments() methods in the cloud_firestore plugin, and is implemented with read from cache first then server.

Getting Started #

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

dependencies:
  firestore_cache: ^0.1.0

Usage #

Before using the plugin, you will need to create a document on Firestore and create a timestamp field in that document. See the screenshot below for an example:

Firestore Screenshot

PLEASE NOTE This plugin does not compare the documents in the cache and the ones in the server to determine if it should fetch data from the server. Instead, it relies on the timestamp field in the document to make that decision. And so your application should implement the logic to update this field if you want to read new data from the server instead of reading it from the cache.

You should also create different timestamp fields for different collections or documents that you are reading.

import 'package:firestore_cache/firestore_cache.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

// This should be the path of the document that you created
final DocumentReference cacheDocRef = Firestore.instance.document('status/status');

// This should be the timestamp field in that document
final String cacheField = 'updatedAt';

final Query query = Firestore.instance.collection('collection');
final QuerySnapshot snapshot = await FirestoreCache.getDocuments(
    query: query,
    cacheDocRef: cacheDocRef,
    firestoreCacheField: cacheField,
);

0.1.1 #

  • Added option to re-fetch document from the server if the cached document is empty

0.1.0 #

  • Initial release

example/lib/main.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firestore_cache/firestore_cache.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firestore Cache Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  final _firestore = Firestore.instance;
  Future<DocumentSnapshot> _futureDoc;
  Future<QuerySnapshot> _futureSnapshot;

  @override
  void initState() {
    super.initState();
    _futureDoc = _getDoc();
    _futureSnapshot = _getDocs();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Firestore Cache Demo')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _buildDoc(),
            _buildDocs(),
          ],
        ),
      ),
    );
  }

  Widget _buildDoc() {
    return FutureBuilder<DocumentSnapshot>(
      future: _futureDoc,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Text(snapshot.error);
        } else if (!snapshot.hasData) {
          return CircularProgressIndicator();
        }

        final DocumentSnapshot doc = snapshot.data;

        return Text('${doc.data['userId']} ${doc.metadata.isFromCache}');
      },
    );
  }

  Widget _buildDocs() {
    return FutureBuilder<QuerySnapshot>(
      future: _futureSnapshot,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Text(snapshot.error);
        } else if (!snapshot.hasData) {
          return CircularProgressIndicator();
        }

        final List<DocumentSnapshot> docs = snapshot.data.documents;

        return Expanded(
          child: ListView(
            children: docs.map((DocumentSnapshot doc) {
              return Text(
                '${doc.data['postId']} ${doc.metadata.isFromCache}',
                textAlign: TextAlign.center,
              );
            }).toList(),
          ),
        );
      },
    );
  }

  Future<DocumentSnapshot> _getDoc() async {
    final DocumentReference docRef = _firestore.document('users/user');
    final DocumentSnapshot doc = await FirestoreCache.getDocument(docRef);

    return doc;
  }

  Future<QuerySnapshot> _getDocs() async {
    final DocumentReference cacheDocRef = _firestore.document('status/status');
    final String cacheField = 'updatedAt';
    final Query query = _firestore.collection('posts');
    final QuerySnapshot snapshot = await FirestoreCache.getDocuments(
      query: query,
      cacheDocRef: cacheDocRef,
      firestoreCacheField: cacheField,
    );

    return snapshot;
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  firestore_cache: ^0.1.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:firestore_cache/firestore_cache.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
63
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]
81
Learn more about scoring.

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

  • Dart: 2.8.4
  • pana: 0.13.14
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform android

Because:

  • package:firestore_cache/firestore_cache.dart that imports:
  • package:shared_preferences/shared_preferences.dart that imports:
  • package:shared_preferences_linux/shared_preferences_linux.dart that declares support for platforms: linux

Package does not support Flutter platform ios

Because:

  • package:firestore_cache/firestore_cache.dart that imports:
  • package:shared_preferences/shared_preferences.dart that imports:
  • package:shared_preferences_linux/shared_preferences_linux.dart that declares support for platforms: linux

Package does not support Flutter platform linux

Because:

  • package:firestore_cache/firestore_cache.dart that imports:
  • package:cloud_firestore/cloud_firestore.dart that declares support for platforms: android, ios, macos, web

Package does not support Flutter platform macos

Because:

  • package:firestore_cache/firestore_cache.dart that imports:
  • package:shared_preferences/shared_preferences.dart that imports:
  • package:shared_preferences_linux/shared_preferences_linux.dart that declares support for platforms: linux

Package does not support Flutter platform web

Because:

  • package:firestore_cache/firestore_cache.dart that imports:
  • package:shared_preferences/shared_preferences.dart that imports:
  • package:shared_preferences_linux/shared_preferences_linux.dart that declares support for platforms: linux

Package does not support Flutter platform windows

Because:

  • package:firestore_cache/firestore_cache.dart that imports:
  • package:shared_preferences/shared_preferences.dart that declares support for platforms: android, ios, linux, macos, web

Package not compatible with SDK dart

Because:

  • firestore_cache that is a package requiring null.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
cloud_firestore ^0.13.0+1 0.13.7
flutter 0.0.0
meta ^1.1.8 1.1.8 1.2.2
shared_preferences ^0.5.7 0.5.8
Transitive dependencies
charcode 1.1.3
cloud_firestore_platform_interface 1.1.2
cloud_firestore_web 0.1.1+2
collection 1.14.12 1.14.13
file 5.2.1
firebase 7.3.0
firebase_core 0.4.5
firebase_core_platform_interface 1.0.4
firebase_core_web 0.1.1+2
flutter_web_plugins 0.0.0
http 0.12.1
http_parser 3.1.4
intl 0.16.1
js 0.6.2
matcher 0.12.8
path 1.7.0
path_provider_linux 0.0.1+2
path_provider_platform_interface 1.0.2
pedantic 1.9.0 1.9.2
platform 2.2.1
plugin_platform_interface 1.0.2
process 3.0.13
quiver 2.1.3
shared_preferences_linux 0.0.2+1
shared_preferences_macos 0.0.1+10
shared_preferences_platform_interface 1.0.4
shared_preferences_web 0.1.2+7
sky_engine 0.0.99
source_span 1.7.0
stack_trace 1.9.5
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
xdg_directories 0.1.0
Dev dependencies
cloud_firestore_mocks ^0.4.3+1
flutter_test