cloud_firestore_rest 0.0.2+1a

  • Readme
  • Changelog
  • Example
  • Installing
  • 60

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

import 'package:flutter/material.dart';
import 'package:global_configuration/global_configuration.dart';

import 'package:cloud_firestore_rest/cloud_firestore_rest.dart';

void main() {
  ///
  /// Configure your Firebase Firestore settings here
  ///
  GlobalConfiguration().loadFromMap({
    'projectId': 'flutter-shop-aec08',
    'webKey': 'AIzaSyDVGNPjOOMaa7kqgTKc4sy15ayVFkmpHHc',
  });
  runApp(TodoApp());
}

class TodoApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Cloud Firestore REST API Example',
      home: TodoList(),
    );
  }
}

class TodoList extends StatefulWidget {
  @override
  _TodoListState createState() => _TodoListState();
}

class _TodoListState extends State<TodoList> {
  bool _isInit = true;
  bool _isBusy = false;
  List<Map<String, dynamic>> _todoItems = [];

  Future<void> _addTodoItem() async {
    try {
      setState(() {
        _isBusy = true;
      });
      final item = await Firestore.add(collection: 'todo', body: {
        'text': 'Item #${_todoItems.length}',
      });

      setState(() {
        _todoItems.add(item);
        _isBusy = false;
      });
    } catch (error) {
      throw error;
    }
  }

  Future<void> _update({
    Map<String, dynamic> item,
    bool delete = false,
  }) async {
    try {
      setState(() {
        _isBusy = true;
      });
      if (delete) {
        await Firestore.delete(
          collection: 'todo',
          id: item['id'],
        );
        _todoItems.removeWhere((_item) => _item['id'] == item['id']);
      } else {
        await Firestore.setAll(
          collection: 'todo',
          id: item['id'],
          body: item,
        );
      }
    } catch (error) {
      print(error);
    }
    setState(() {
      _isBusy = false;
    });
  }

  Widget _buildTodoList() {
    return ListView.builder(
      itemBuilder: (context, index) {
        if (index < _todoItems.length) {
          return _buildTodoItem(_todoItems[index]);
        }
        return null;
      },
    );
  }

  Widget _buildTodoItem(Map<String, dynamic> item) {
    return ListTile(
      title: Text(item['text']),
      onTap: () async {
        if (item['text'].contains('Done')) {
          await _update(item: item, delete: true);
        } else {
          item['text'] += ' Done';
          await _update(item: item);
        }
      },
    );
  }

  Future<List<Map<String, dynamic>>> _getTodos() async {
    final items = await Firestore.get(
      collection: 'todo',
      sortField: 'text',
    );
    return items;
  }

  @override
  void didChangeDependencies() {
    if (_isInit) {
      _isBusy = true;
      _getTodos().then((items) {
        _todoItems = items;
      }).catchError((error) {
        print(error);
      }).whenComplete(() {
        setState(() {
          _isInit = false;
          _isBusy = false;
        });
      });
    }
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          children: <Widget>[
            Text('Cloud Firestore REST API Example'),
            if (_isBusy)
              Container(
                child: CircularProgressIndicator(
                  backgroundColor: Colors.white,
                  strokeWidth: 2.0,
                ),
              ),
          ],
        ),
      ),
      body: _buildTodoList(),
      floatingActionButton: FloatingActionButton(
        onPressed: _addTodoItem,
        tooltip: 'Add task',
        child: Icon(Icons.add),
      ),
    );
  }
}

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]
23
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]
60
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
  • Flutter: 1.17.5

Analysis suggestions

Package not compatible with SDK dart

Because:

  • cloud_firestore_rest that is a package requiring null.

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.1
Transitive dependencies
charcode 1.1.3
collection 1.14.12 1.14.13
http_parser 3.1.4
meta 1.1.8 1.2.2
path 1.7.0
pedantic 1.9.0 1.9.2
sky_engine 0.0.99
source_span 1.7.0
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
Dev dependencies
flutter_test