cloud_firestore_vm 0.0.7

  • Readme
  • Changelog
  • Example
  • Installing
  • 63

Firebase Firestore for Dart #

A Dart port of the Firebase Firestore SDK to use the Cloud Firestore API.

Note: This library is still under development, and some APIs might not be available yet or work correctly. Please feel free to open an issue here or even a pull requests if you feel brave.

Setup #

To use this plugin:

  1. Using the Firebase Console, add an Android app to your project: Follow the assistant, download the generated google-services.json file and place it inside android/app. Next, modify the android/build.gradle file and the android/app/build.gradle file to add the Google services plugin as described by the Firebase assistant. Ensure that your android/build.gradle file contains the maven.google.com as described here.
  2. Using the Firebase Console, add an iOS app to your project: Follow the assistant, download the generated GoogleService-Info.plist file, open ios/Runner.xcworkspace with Xcode, and within Xcode place the file inside ios/Runner. Don't follow the steps named "Add Firebase SDK" and "Add initialization code" in the Firebase assistant.
  3. Add firebase_firestore as a dependency in your pubspec.yaml file.

Usage #

import 'package:cloud_firestore/cloud_firestore.dart';

Adding a new DocumentReference:

FirebaseFirestore.instance
    .collection('books')
    .document()
    .set({'title': 'title', 'author': 'author'});

Performing a query:

FirebaseFirestore.instance
    .collection('talks')
    .whereEqualTo('topic', 'flutter')
    .snapshots
    .listen((data) => data.documents.forEach((doc) => print(doc['title'])));

Running a transaction:

final DocumentReference postRef = FirebaseFirestore.instance.document('posts/123');
FirebaseFirestore.instance.runTransaction((Transaction tx) async {
  final DocumentSnapshot postSnapshot = await tx.get(postRef);
  if (postSnapshot.exists) {
    tx.update(postRef, <String, dynamic>{
      'likesCount': postSnapshot.getInt('likesCount') + 1
    });
  }
});

[0.0.7] - April 22, 2020 #

  • make Firestore.newInstance register the new instance with the multi db component
  • add warning in case of not initializing FirebaseAuth prior to calling Firestore.instance

[0.0.6] - April 21, 2020 #

  • fix auth provider picker logic
  • fix exporting Source

[0.0.5] - April 18, 2020 #

  • fix null bool

[0.0.4] - April 18, 2020 #

  • disable verbose logging
  • make sql connection not exclusive so we don't break hot reload

[0.0.3] - April 18, 2020 #

  • fix return when garbage collection kicks in

[0.0.2] - April 18, 2020 #

  • update export statements

[0.0.1] - April 18, 2020 #

  • initial release

example/lib/main.dart

// Copyright 2017, the Chromium project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';
import 'dart:io';

import 'package:cloud_firestore_vm/cloud_firestore_vm.dart';
import 'package:cloud_firestore_vm_example/platform_dependencies.dart';
import 'package:firebase_auth_vm/firebase_auth_vm.dart';
import 'package:firebase_core_vm/firebase_core_vm.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'database.dart' as db;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final SharedPreferences preferences = await SharedPreferences.getInstance();
  final PlatformDependencies platform = PlatformDependencies(preferences);
  final FirebaseApp app =
      FirebaseApp.withOptions(options, dependencies: platform);
  if (FirebaseAuth.instance.currentUser == null) {
    await FirebaseAuth.instance.signInAnonymously();
  }
  await Firestore.getInstance(app, openDatabase: db.Database.create);

  runApp(
    MaterialApp(
      title: 'Firestore Example',
      home: MyHomePage(firestore: Firestore.instance),
    ),
  );
}

class MessageList extends StatelessWidget {
  const MessageList({Key key, this.firestore}) : super(key: key);

  final Firestore firestore;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: firestore
          .collection('messages')
          .orderBy('created_at', Direction.descending)
          .snapshots,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (!snapshot.hasData) {
          return const Text('Loading...');
        }
        final int messageCount = snapshot.data.documents.length;
        return ListView.builder(
          itemCount: messageCount,
          itemBuilder: (_, int index) {
            final DocumentSnapshot document = snapshot.data.documents[index];
            final dynamic message = document['message'];
            return ListTile(
              trailing: IconButton(
                onPressed: () => document.reference.delete(),
                icon: const Icon(Icons.delete),
              ),
              title: Text(
                message != null ? message.toString() : '<No message retrieved>',
              ),
              subtitle: Text('Message ${index + 1} of $messageCount'),
            );
          },
        );
      },
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key key, this.firestore}) : super(key: key);

  final Firestore firestore;

  CollectionReference get messages => firestore.collection('messages');

  Future<void> _addMessage() async {
    await messages.add(<String, dynamic>{
      'message': 'Hello world!',
      'created_at': FieldValue.serverTimestamp(),
    });
  }

  Future<void> _runTransaction() async {
    await firestore.runTransaction((Transaction transaction) async {
      final QuerySnapshot allDocs =
          await firestore.collection('messages').get();
      final List<DocumentSnapshot> toBeRetrieved =
          allDocs.documents.sublist(allDocs.documents.length ~/ 2);
      final List<DocumentSnapshot> toBeDeleted =
          allDocs.documents.sublist(0, allDocs.documents.length ~/ 2);
      await Future.forEach(toBeDeleted, (DocumentSnapshot snapshot) async {
        transaction.delete(snapshot.reference);
      });

      await Future.forEach(toBeRetrieved, (DocumentSnapshot snapshot) async {
        transaction.update(snapshot.reference, <String, dynamic>{
          'message': 'Updated from Transaction',
          'created_at': FieldValue.serverTimestamp()
        });
      });
    });

    await Future.forEach(List<int>.generate(2, (int index) => index),
        (int item) async {
      await firestore.runTransaction((Transaction transaction) async {
        await Future.forEach(List<int>.generate(10, (int index) => index),
            (int item) async {
          transaction.set(
            firestore.collection('messages').document(),
            <String, dynamic>{
              'message': 'Created from Transaction $item',
              'created_at': FieldValue.serverTimestamp()
            },
          );
        });
      });
    });
  }

  Future<void> _runBatchWrite() async {
    final WriteBatch batchWrite = firestore.batch();
    final QuerySnapshot querySnapshot = await firestore
        .collection('messages')
        .orderBy('created_at')
        .limit(12)
        .get();

    querySnapshot.documents
        .sublist(0, querySnapshot.documents.length - 3)
        .forEach((DocumentSnapshot doc) {
      batchWrite.update(doc.reference, <String, dynamic>{
        'message': 'Batched message',
        'created_at': FieldValue.serverTimestamp()
      });
    });
    batchWrite
      ..set(
        firestore.collection('messages').document(),
        <String, dynamic>{
          'message': 'Batched message created',
          'created_at': FieldValue.serverTimestamp()
        },
      )
      ..delete(
          querySnapshot.documents[querySnapshot.documents.length - 2].reference)
      ..delete(querySnapshot.documents.last.reference);
    return batchWrite.commit();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Firestore Example'),
        actions: <Widget>[
          FlatButton(
            onPressed: _runTransaction,
            child: const Text('Run Transaction'),
          ),
          FlatButton(
            onPressed: _runBatchWrite,
            child: const Text('Batch Write'),
          )
        ],
      ),
      body: MessageList(firestore: firestore),
      floatingActionButton: FloatingActionButton(
        onPressed: _addMessage,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

FirebaseOptions get options {
  if (Platform.isAndroid) {
    return FirebaseOptions(
      applicationId: '1:233259864964:android:b2ec71b130a3170cd583d1',
      gcmSenderId: '297855924061',
      apiKey: 'AIzaSyAM1bGAY-Bd4onFPFb2dBCJA3kx0eiWnSg',
      projectId: 'flutter-sdk',
    );
  } else if (Platform.isIOS) {
    return FirebaseOptions(
      applicationId: '1:233259864964:ios:fff621fea008bff1d583d1',
      gcmSenderId: '233259864964',
      apiKey: 'AIzaSyBguTk4w2Xk2LD0mSdB2Pi9LTtt5BeAE6U',
      projectId: 'flutter-sdk',
    );
  } else {
    return FirebaseOptions(
      applicationId:
          '1:233259864964:macos:0bdc69800dd31cde15627229f39a6379865e8be1',
      gcmSenderId: '233259864964',
      apiKey: 'AIzaSyBQgB5s3n8WvyCOxhCws-RVf3C-6VnGg0A',
      projectId: 'flutter-sdk',
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  cloud_firestore_vm: ^0.0.7

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or 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:cloud_firestore_vm/cloud_firestore_vm.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
50
Health:
Code health derived from static analysis. [more]
75
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
63
Learn more about scoring.

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

  • Dart: 2.8.4
  • pana: 0.13.14

Analysis suggestions

Package not compatible with runtime flutter-web on web

Because:

  • package:cloud_firestore_vm/cloud_firestore_vm.dart that imports:
  • package:cloud_firestore_vm/src/firebase/firestore/write_batch.dart that imports:
  • package:cloud_firestore_vm/src/firebase/firestore/util/util.dart that imports:
  • package:grpc/grpc.dart that imports:
  • package:grpc/src/shared/streams.dart that imports:
  • package:http2/transport.dart that imports:
  • package:http2/src/hpack/hpack.dart that imports:
  • package:http2/src/hpack/huffman_table.dart that imports:
  • package:http2/src/hpack/huffman.dart that imports:
  • dart:io

Package not compatible with runtime js

Because:

  • package:cloud_firestore_vm/cloud_firestore_vm.dart that imports:
  • package:cloud_firestore_vm/src/firebase/firestore/write_batch.dart that imports:
  • package:cloud_firestore_vm/src/firebase/firestore/util/util.dart that imports:
  • package:grpc/grpc.dart that imports:
  • package:grpc/src/shared/streams.dart that imports:
  • package:http2/transport.dart that imports:
  • package:http2/src/hpack/hpack.dart that imports:
  • package:http2/src/hpack/huffman_table.dart that imports:
  • package:http2/src/hpack/huffman.dart that imports:
  • dart:io

Health suggestions

Fix lib/src/proto/google/firestore/v1/firestore.pbjson.dart. (-25 points)

Analysis of lib/src/proto/google/firestore/v1/firestore.pbjson.dart reported 183 hints, including:

line 8 col 33: Avoid const keyword.

line 10 col 8: Avoid const keyword.

line 11 col 5: Avoid const keyword.

line 12 col 5: Avoid const keyword.

line 13 col 5: Avoid const keyword.

Fix lib/src/proto/google/firestore/v1/query.pbjson.dart. (-25 points)

Analysis of lib/src/proto/google/firestore/v1/query.pbjson.dart reported 80 hints, including:

line 8 col 30: Avoid const keyword.

line 10 col 8: Avoid const keyword.

line 11 col 5: Avoid const keyword.

line 12 col 5: Avoid const keyword.

line 13 col 5: Avoid const keyword.

Fix lib/src/proto/google/firestore/v1/write.pbjson.dart. (-23.33 points)

Analysis of lib/src/proto/google/firestore/v1/write.pbjson.dart reported 53 hints, including:

line 8 col 20: Avoid const keyword.

line 10 col 8: Avoid const keyword.

line 11 col 5: Avoid const keyword.

line 12 col 5: Avoid const keyword.

line 13 col 5: Avoid const keyword.

Fix additional 54 files with analysis or formatting issues. (-93.28 points)

Additional issues in the following files:

  • lib/src/proto/google/firestore/v1/document.pbjson.dart (39 hints)
  • lib/src/proto/google/protobuf/wrappers.pbjson.dart (27 hints)
  • lib/src/proto/google/protobuf/struct.pbjson.dart (25 hints)
  • lib/src/proto/google/firestore/v1/common.pbjson.dart (24 hints)
  • lib/src/proto/google/api/http.pbjson.dart (21 hints)
  • lib/src/proto/firebase/firestore/proto/maybe_document.pbjson.dart (16 hints)
  • lib/src/proto/firebase/firestore/proto/target.pbjson.dart (16 hints)
  • lib/src/proto/firebase/firestore/proto/mutation.pbjson.dart (10 hints)
  • lib/src/proto/google/rpc/status.pbjson.dart (5 hints)
  • lib/src/proto/google/protobuf/any.pbjson.dart (4 hints)
  • lib/src/proto/google/protobuf/timestamp.pbjson.dart (4 hints)
  • lib/src/proto/google/type/latlng.pbjson.dart (4 hints)
  • lib/src/firebase/firestore/document_snapshot.dart (1 hint)
  • lib/src/proto/google/protobuf/empty.pbjson.dart (1 hint)
  • lib/src/firebase/firestore/auth/firebase_auth_credentials_provider.dart (Run dartfmt to format lib/src/firebase/firestore/auth/firebase_auth_credentials_provider.dart.)
  • lib/src/firebase/firestore/core/transaction.dart (Run dartfmt to format lib/src/firebase/firestore/core/transaction.dart.)
  • lib/src/firebase/firestore/document_reference.dart (Run dartfmt to format lib/src/firebase/firestore/document_reference.dart.)
  • lib/src/firebase/firestore/model/value/array_value.dart (Run dartfmt to format lib/src/firebase/firestore/model/value/array_value.dart.)
  • lib/src/firebase/firestore/server_timestamp_behavior.dart (Run dartfmt to format lib/src/firebase/firestore/server_timestamp_behavior.dart.)
  • lib/src/proto/firebase/firestore/proto/maybe_document.pb.dart (Run dartfmt to format lib/src/proto/firebase/firestore/proto/maybe_document.pb.dart.)
  • lib/src/proto/firebase/firestore/proto/maybe_document.pbenum.dart (Run dartfmt to format lib/src/proto/firebase/firestore/proto/maybe_document.pbenum.dart.)
  • lib/src/proto/firebase/firestore/proto/mutation.pb.dart (Run dartfmt to format lib/src/proto/firebase/firestore/proto/mutation.pb.dart.)
  • lib/src/proto/firebase/firestore/proto/mutation.pbenum.dart (Run dartfmt to format lib/src/proto/firebase/firestore/proto/mutation.pbenum.dart.)
  • lib/src/proto/firebase/firestore/proto/target.pb.dart (Run dartfmt to format lib/src/proto/firebase/firestore/proto/target.pb.dart.)
  • lib/src/proto/firebase/firestore/proto/target.pbenum.dart (Run dartfmt to format lib/src/proto/firebase/firestore/proto/target.pbenum.dart.)
  • lib/src/proto/google/api/annotations.pb.dart (Run dartfmt to format lib/src/proto/google/api/annotations.pb.dart.)
  • lib/src/proto/google/api/annotations.pbenum.dart (Run dartfmt to format lib/src/proto/google/api/annotations.pbenum.dart.)
  • lib/src/proto/google/api/annotations.pbjson.dart (Run dartfmt to format lib/src/proto/google/api/annotations.pbjson.dart.)
  • lib/src/proto/google/api/http.pb.dart (Run dartfmt to format lib/src/proto/google/api/http.pb.dart.)
  • lib/src/proto/google/api/http.pbenum.dart (Run dartfmt to format lib/src/proto/google/api/http.pbenum.dart.)
  • lib/src/proto/google/firestore/v1/common.pb.dart (Run dartfmt to format lib/src/proto/google/firestore/v1/common.pb.dart.)
  • lib/src/proto/google/firestore/v1/common.pbenum.dart (Run dartfmt to format lib/src/proto/google/firestore/v1/common.pbenum.dart.)
  • lib/src/proto/google/firestore/v1/document.pb.dart (Run dartfmt to format lib/src/proto/google/firestore/v1/document.pb.dart.)
  • lib/src/proto/google/firestore/v1/document.pbenum.dart (Run dartfmt to format lib/src/proto/google/firestore/v1/document.pbenum.dart.)
  • lib/src/proto/google/firestore/v1/firestore.pb.dart (Run dartfmt to format lib/src/proto/google/firestore/v1/firestore.pb.dart.)
  • lib/src/proto/google/firestore/v1/firestore.pbenum.dart (Run dartfmt to format lib/src/proto/google/firestore/v1/firestore.pbenum.dart.)
  • lib/src/proto/google/firestore/v1/query.pb.dart (Run dartfmt to format lib/src/proto/google/firestore/v1/query.pb.dart.)
  • lib/src/proto/google/firestore/v1/query.pbenum.dart (Run dartfmt to format lib/src/proto/google/firestore/v1/query.pbenum.dart.)
  • lib/src/proto/google/firestore/v1/write.pb.dart (Run dartfmt to format lib/src/proto/google/firestore/v1/write.pb.dart.)
  • lib/src/proto/google/firestore/v1/write.pbenum.dart (Run dartfmt to format lib/src/proto/google/firestore/v1/write.pbenum.dart.)
  • lib/src/proto/google/protobuf/any.pb.dart (Run dartfmt to format lib/src/proto/google/protobuf/any.pb.dart.)
  • lib/src/proto/google/protobuf/any.pbenum.dart (Run dartfmt to format lib/src/proto/google/protobuf/any.pbenum.dart.)
  • lib/src/proto/google/protobuf/empty.pb.dart (Run dartfmt to format lib/src/proto/google/protobuf/empty.pb.dart.)
  • lib/src/proto/google/protobuf/empty.pbenum.dart (Run dartfmt to format lib/src/proto/google/protobuf/empty.pbenum.dart.)
  • lib/src/proto/google/protobuf/struct.pb.dart (Run dartfmt to format lib/src/proto/google/protobuf/struct.pb.dart.)
  • lib/src/proto/google/protobuf/struct.pbenum.dart (Run dartfmt to format lib/src/proto/google/protobuf/struct.pbenum.dart.)
  • lib/src/proto/google/protobuf/timestamp.pb.dart (Run dartfmt to format lib/src/proto/google/protobuf/timestamp.pb.dart.)
  • lib/src/proto/google/protobuf/timestamp.pbenum.dart (Run dartfmt to format lib/src/proto/google/protobuf/timestamp.pbenum.dart.)
  • lib/src/proto/google/protobuf/wrappers.pb.dart (Run dartfmt to format lib/src/proto/google/protobuf/wrappers.pb.dart.)
  • lib/src/proto/google/protobuf/wrappers.pbenum.dart (Run dartfmt to format lib/src/proto/google/protobuf/wrappers.pbenum.dart.)
  • lib/src/proto/google/rpc/status.pb.dart (Run dartfmt to format lib/src/proto/google/rpc/status.pb.dart.)
  • lib/src/proto/google/rpc/status.pbenum.dart (Run dartfmt to format lib/src/proto/google/rpc/status.pbenum.dart.)
  • lib/src/proto/google/type/latlng.pb.dart (Run dartfmt to format lib/src/proto/google/type/latlng.pb.dart.)
  • lib/src/proto/google/type/latlng.pbenum.dart (Run dartfmt to format lib/src/proto/google/type/latlng.pbenum.dart.)

Maintenance issues and suggestions

Support latest dependencies. (-10 points)

The version constraint in pubspec.yaml does not support the latest published versions for 1 dependency (rxdart).

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
_firebase_database_collection_vm ^0.0.2 0.0.2
_firebase_internal_vm ^0.0.2 0.0.2
async ^2.4.1 2.4.2
collection ^1.14.12 1.14.13 1.15.0-nullsafety
firebase_core_vm ^0.0.4 0.0.4
fixnum ^0.10.11 0.10.11
grpc ^2.1.3 2.2.0
meta ^1.1.8 1.2.2 1.3.0-nullsafety
path ^1.6.4 1.7.0
pedantic ^1.9.0 1.9.2
protobuf ^1.0.1 1.0.1
rxdart ^0.23.1 0.23.1 0.24.1
semaphore ^0.1.4 0.1.4
Transitive dependencies
charcode 1.1.3
convert 2.1.1
crypto 2.1.5
googleapis_auth 0.2.12
http 0.12.1
http2 1.0.0
http_parser 3.1.4
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.2.0 1.3.0-nullsafety
Dev dependencies
mockito ^4.1.1
moor_ffi ^0.4.0
test ^1.14.2
uuid ^2.0.4