cloud_firestore_rest 0.0.2+1a

Cloud Firestore Package for Flutter - Work in Progress #

A Flutter Package to use the Cloud Firestore API for cross platform Flutter Apps.

Setup #

To use this package:

  1. Using the Firebase Console, add a web app to your project. Note Your app may be intended to run on IOS, Android, MacOS, Linux , Web or Windows platforms (or all of them) - you still add your app as a web app in firebase
  1. Go to Project Settings , copy down

    1. Project ID
    2. Web API Key
  2. Add cloud_firestore_rest and global_configuration as a dependency in your pubspec.yaml file.

  3. Edit lib/main.dart and edit code

    +import 'package:global_configuration/global_configuration.dart';
    ...
    
    void main()  {
     + GlobalConfiguration().loadFromMap({
     +  'projectId': '<project ID>',
     +  'webKey': 'web API key',
     +});
      runApp(MyApp());
    }
    ...
    
    

Of course you may use any of the GlobalConfiguration load methods of your choice to configure your app. The package expects projectId and webKey to be available as part of global configuration.

Usage #

Authentication #

You can register your users in firebase and use googleapis identitytoolkit to login and logout users.

try {
Map<String, dynamic> response = await Firestore.signInOrSignU[(
  email: 'abcd@efg.com',
  password: '123456',
  action: AuthAction.signUp **OR** AuthAction.signInWithPassword,
);
} catch (error) {
  // handle error
}

The returned response contains

  • firebase userId
  • auth token
  • login expiry

Read from firestore #

Performing a query #


import 'package:cloud_firestore_rest/cloud_firestore_rest.dart';

Future<List<Item>> Firestore.get({List<Query> query)}) {
  List<Item> items;
  final documents = await Firestore.get(
    collection: 'items',
    query: query,
    );
  documents.map((doc) => _items.add(Item.fromJson(doc)));
  return items;
}

...

try {
List<Item> items = await Firestore.get(query: [
  Query(field: 'orderDate', op: FieldOp.GREATER, value: searchDate),
  Query(field: 'customerId', value: searchId),
]);
} catch(error) {
  //handle error

Get all documents from a collection #

Call Firestore.get(collection: 'collectionId') without supplying a query argument to get all the documents from the collection.

Get a specific document #

...
Map<String, dynamic> document = await Firestore.getDocument(
  collection: 'items', id: searchId,
  ); // returns null if not found
Item item = Item.fromJson(document);
...


Write to firestore #

Add new Collection/document #

Creates a new collection if collection does not exist. Adds the document if the document does not exist. Returns created document.


try {
  final document = await Firestore.add(
    collection: 'orders',
    body: order.toJson
    );
  order.id = docurment['id'];
} catch (error) {
  // handle error
}

Update document #

Update a document, add if the document does not exist #

Updates only the fields passed via the body argument. The fields can be new - and need not be part of the existing document.

If document is not found and the optional argument addNew is true, adds the document to the collection.

If id is not supplied, firestore creates one for the document.

Note: If an entire document is not passed to this function, the API will not throw error, instead will write a truncated document.

...

try {
  await Firstore.setAll(
    collection: 'orders',
    id: order.id,
    body: order.toJson,
    addNew: true,
  );
} catch(error) {
  // handle error
}

Delete document #

Deletes the document in the collection specified.

Throws error if document does not exist.

...

try {
  await Firstore.delete(
    collection: 'orders',
    id: order.id,
  );
} catch(error) {
  // handle error
}

[0.0.1] - 2019-12-11

  • A brief description of the package A Flutter Package to use the Cloud Firestore API by cross platform Flutter Apps.
  • TODO: Describe initial release.

[0.0.2] - 2020-01-15

Added Firebase authentication

[0.0.2+1] - 2020-01-16

  • Corrected handling of DateTime, Map and List types

[0.0.2+1a] - 2020-01-16

  • Minor tweaks

example/README.md

Cloud Firestore REST API for Flutter #

A Flutter Package to use the Cloud Firestore API by cross platform Flutter Apps.

This package supports Android, IOS, Linux, macOs platforms.

The package has not been tested on Windows platform but there should be no technical reason for it not to function correctly in Windows environment.

Contents #

Setup #

To use this package:

  1. Using the Firebase Console, add a web app to your project.

  2. Go to Project Settings , copy

    1. Project ID
    2. Web API Key
  3. Add cloud_firestore_rest and global_configuration as a dependency in your pubspec.yaml file.

  4. Edit your app's lib/main.dart

    +import 'package:global_configuration/global_configuration.dart';
    ...
    
    void main()  {
     + GlobalConfiguration().loadFromMap({
     +  'projectId': '<project ID>',
     +  'webKey': 'web API key',
     +});
      runApp(MyApp());
    }
    ...
    
    

Of course, you may use any of the GlobalConfiguration load methods of your choice to configure your app. The package expects projectId and webKey to be available as part of global configuration.

Read from firestore #

Get Documents #

Firestore.get() may be used to read all documents in a collection or any documents that meet specified filters.

Parameters #

collection string required

name of the collection root. example: 'users', 'users/seniors'

sort List<Map<String, String>>

To specifiy one or more sort fields

  sort: [
    { 'field: 'date', 'direction': 'ASCENDING' },
    { 'field: 'orderNumber' },
  ],

_Alternatively, If it's just one field you can use the sortField and sortOrder parameters.Direction can be either 'ASCENDING' or 'DESCENDING'.

query List<Map<String, dynamic>>

Multiple filters can be specified by using the query parameter.

Multiple filters can be specified. As on date Firestore supports joining multiple filter conditions only using 'AND'.

  query: [
    Query(field: 'age', op: 'EQUAL', value: 31),
    Query(...)
  ],

Field logical operator - op can be omitted if you are testing equality. The op can be any one of the following strings:

LESS_THAN, LESS_THAN_OR_EQUAL, GREATER_THAN, GREATER_THAN_OR_EQUAL, EQUAL, ARRAY_CONTAINS, IN, ARRAY_CONTAINS_ANY,

   Future<List<Map<String, dynamic>>> get({
    @required String collection,
    String sortField,
    String sortOrder = 'ASCENDING',
    String keyField,
    String keyOp = 'EQUAL',
    String keyValue,
    List<Map<String, dynamic>> sort,
    List<Query> query,
  })

Get() Usage #

import 'package:cloud_firestore_rest/cloud_firestore_rest.dart';

try {
List<Item> items = await getItems(query: [
  Query(field: 'orderDate', op: FieldOp.GREATER_THAN, value: searchDate),
  Query(field: 'customerId', value: searchId),
]);
} catch(error) {
  //handle error
}

Get a document by ID #

Cloud Firestore REST API generates a unique ID for each document stored in a collection.

If the specified document could not be found, API throws an error.

Usage #

try {
  final Map<String, dynamic> document = await Firestore.getDocument(
    collection: 'users',
    id: 'ACDZ638V565577'
  );
  // found!
} catch(error) {
  if(error.contains('NOT FOUND)) {
    // not found
  }
  // some other error
}

Create new Document #

Adds a new document to the specified collection. Creates a new collection if the collection did not exist.

The newly added document is returned along with the id created by Firestore.


try {
  final Map<String, dynamic> document = await Firestore.add(
    collection: 'orders',
    body: order.toJson
    );
  // document['id] contains the newly created document's id.
} catch (error) {
  // handle error
}

Update document #

Updates entire document. If document is not found, adds the document to the collection.

Note: If an entire document is not passed to this function, the API will not throw error, instead will write a truncated document.

...

try {
  await Firstore.update(
    collection: 'orders',
    id: order.id,
    body: order.toJson,
  );
} catch(error) {
  // handle error
}

Delete document #

Deletes the document in the collection specified.

Throws error if document does not exist.

...

try {
  await Firstore.delete(
    collection: 'orders',
    id: order.id,
  );
} catch(error) {
  // handle error
}

Authentication #

Signup #

SignUp registers a new email with firebase

...

try {
final Map<String, dynamic> auth = await Firestore.signInOrSignUp(
  email: 'test1@test.com',
  password: '123456',
  action: AuthAction.signUp,
);
} catch(error) {
  // handle errors including id already exists
}

Signin #

...

try {
final Map<String, dynamic> auth = await Firestore.signInOrSignUp(
  email: 'test1@test.com',
  password: '123456',
  action: AuthAction.signInWithPassword
);
} catch(error) {
  // handle errors including id already exists
}

On successful authentication, the function returns a map containing idToken, expiryDate, userId, email as keys.

Use this package as a library

1. Depend on it

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


dependencies:
  cloud_firestore_rest: ^0.0.2+1a

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

We analyzed this package on Feb 19, 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

Health suggestions

Format lib/cloud_firestore_rest.dart.

Run flutter format to format lib/cloud_firestore_rest.dart.

Maintenance suggestions

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.3.0 <3.0.0
flutter 0.0.0
global_configuration ^1.4.0 1.5.0
http ^0.12.0+2 0.12.0+4
Transitive dependencies
async 2.4.0
charcode 1.1.3
collection 1.14.11 1.14.12
http_parser 3.1.3
meta 1.1.8
path 1.6.4
pedantic 1.9.0
sky_engine 0.0.99
source_span 1.6.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test