How to use Cloud Firestore with Flutter

Atul Sharma
5 min readJun 20, 2019

--

In one of my previous blogs i had discussed about using Firebase realtime database with flutter. Now Firebase comes up with a more advanced version of it as Cloud Firestore. I will show you step by steps how we can use Cloud Firestore in Flutter.

Cloud Firestore

Cloud Firestore is also a NoSQL Database like realtime database, but the difference is in the structure of data storage. Realtime database stores data in JSON tree. In Cloud firestore we are having Collection. A collection can have any number of Documents, these Documents contains data. Cloud Firestore scales automatically, its current scaling limit is around 1 million concurrent connections and approx. 10,000 writes operations /second.

Creating a new Project on Firebase

  1. Create a firebase project in firebase console.

https://console.firebase.google.com

2. Add two apps one for android and other for IOS

iOS

  • Register IOS app to firebase with the bundle id of the App
  • Download GoogleService-info for your app and add it to your project folder.
  • complete next steps on firebase console.

Android

  • Register you android app
  • Download the config file google-services.json and put it in the app module of android project.

Create Database

On firebase console from the left menu select Database option to create Cloud Firestore database.

Select security rules for database, for our demo purpose let us select test mode, it ill make the public database, any one can read and write to this database.

Create Flutter project

  1. Use the flutter create command to create a new project.
$ flutter create flutter_with_firebase

2. Open ios/Runner.xcworkspace. Save GoogleService-info.plist in Runner folder

Similarly open Android Studio and put google-services.json file in the app module of android project.

3. In your IDE or editor, open the file pubspec.yaml. Add dependency for cloud_firestore and save the file.

dependencies:
flutter:
sdk:
flutter
cloud_firestore: ^0.11.0+2

4. From the project directory, run the following command.

flutter packages get

Setup

  1. Import dependency for firestore.
import 'package:cloud_firestore/cloud_firestore.dart';

2. Create databaseReference object to work with database.

final databaseReference = Firestore.instance;

3. Create a screen with buttons for CRUD operations.

Create Collection and Insert Document

In Firestore, data resides in document. Collections contains these document. In our case we will create a collection named “books” and add documents to this collection, than add data in document.

1. On click of “Create Record” button, createRecord() method is invoked.

RaisedButton(
child: Text('Create Record'),
onPressed: () {
createRecord();
},
),

2. In createRecord(), we create two demo records in database.

void createRecord() async {
await databaseReference.collection("books")
.document("1")
.setData({
'title': 'Mastering Flutter',
'description': 'Programming Guide for Dart'
});

DocumentReference ref = await databaseReference.collection("books")
.add({
'title': 'Flutter in Action',
'description': 'Complete Programming Guide to learn Flutter'
});
print(ref.documentID);
}

when we use collection(“books”).document(“1”) a document is created in collection named “books” and using setData() we have created data in that document.

when we use collection(“books”) .add(), it has done the same but the document name is randomly generated by firestore as we have not specified.

Retrieve and Display Snapshot

In order to view the data, we have to retrieve all documents or particular document of that collection. For retrieving particular document we have to specify document id.

void getData() {
databaseReference
.collection("books")
.getDocuments()
.then((QuerySnapshot snapshot) {
snapshot.documents.forEach((f) => print('${f.data}}'));
});
}

3. Output on console is

I/flutter : {title: Flutter in Action, description: Complete Programming Guide to learn Flutter}}
I/flutter : {title: Mastering Flutter, description: Programming Guide for Dart}}

Update Data in Document

void updateData() {
try {
databaseReference
.collection('books')
.document('1')
.updateData({'description': 'Head First Flutter'});
} catch (e) {
print(e.toString());
}
}

It updates description of document id 1 to ‘Head First Flutter

Delete Document

void deleteData() {
try {
databaseReference
.collection('books')
.document('1')
.delete();
} catch (e) {
print(e.toString());
}
}

2. It deletes document 1 from the collection named books.

Complete Code

import 'package:flutter/material.dart';

import 'package:cloud_firestore/cloud_firestore.dart';

void main() => runApp(new MediaQuery(
data: new MediaQueryData(), child: new MaterialApp(home: new MyApp())));

class MyApp extends StatelessWidget {
final databaseReference = Firestore.instance;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('FireStore Demo'),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
RaisedButton(
child: Text('Create Record'),
onPressed: () {
createRecord();
},
),
RaisedButton(
child: Text('View Record'),
onPressed: () {
getData();
},
),
RaisedButton(
child: Text('Update Record'),
onPressed: () {
updateData();
},
),
RaisedButton(
child: Text('Delete Record'),
onPressed: () {
deleteData();
},
),
],
)), //center
);
}

void createRecord() async {
await databaseReference.collection("books")
.document("1")
.setData({
'title': 'Mastering Flutter',
'description': 'Programming Guide for Dart'
});

DocumentReference ref = await databaseReference.collection("books")
.add({
'title': 'Flutter in Action',
'description': 'Complete Programming Guide to learn Flutter'
});
print(ref.documentID);
}

void getData() {
databaseReference
.collection("books")
.getDocuments()
.then((QuerySnapshot snapshot) {
snapshot.documents.forEach((f) => print('${f.data}}'));
});
}

void updateData() {
try {
databaseReference
.collection('books')
.document('1')
.updateData({'description': 'Head First Flutter'});
} catch (e) {
print(e.toString());
}
}

void deleteData() {
try {
databaseReference
.collection('books')
.document('1')
.delete();
} catch (e) {
print(e.toString());
}
}
}

--

--

Responses (8)