Firebase Firestore CRUD Operations

Introduction

 
In this article, we will understand the Firestore setup in Firebase and integrate Firestore database in Flutter. We will perform CRUD operations using Flutter in Firestore.
 
Firebase is a Google Cloud Platform which provides cloud services like authentication, real-time database (NoSQL database), storage (Image, audio, video, etc.), Hosting, Cloud Functions, Analytics, etc. We have already discussed authentication in my other articles. If you haven’t read it yet, you can check it here.
 
Now, we will understand the Firestore implementation in Flutter.
 

Prerequisites (Firebase Project Setup)

  1. To set up a Firebase project, please check my other article and follow the first 2 steps. Please note that you need to follow only the first 2 steps.
  2. Now, in a Firebase project, go to the database tab and add a new Firestore database and select region to create it.
  3. You need to add a root collection. By clicking “Start Collection”, you can add it. Click on "Start Collection" and give the Collection Id as students.
You are all done with setting the Firebase project.
 

CRUD Operation in Flutter

 
Open the pubspec.yaml file in your project and add the following dependencies into it.
  1. dependencies:  
  2. flutter:  
  3. sdk: flutter  
  4. cupertino_icons: ^0.1.2  
  5. cloud_firestore: ^0.12.7  
Save the file and run the flutter pub get command on terminal.
 
We will take some important topics that we need to understand. Download the full source code attached with this article. Following are those topics -
 
Go to main.dart and import,
  1. import 'package:cloud_firestore/cloud_firestore.dart';  
Initialize the Firebase instance.
  1. final db = Firestore.instance;  
To add a new student in students collection (we have created in Firestore).
  1. Future < void > addStudent() async {  
  2.     await db.collection("students").add({  
  3.         'name': _studentName,  
  4.         'age'int.parse(_studentAge),  
  5.     }).then((documentReference) {  
  6.         print(documentReference.documentID);  
  7.         clearForm();  
  8.     }).catchError((e) {  
  9.         print(e);  
  10.     });  
  11. }  
Edit student information
  1. Future < void > editStudent() async {  
  2.     await db.collection("students").document(docIdToUpdate).updateData({  
  3.         'name': _studentName,  
  4.         'age'int.parse(_studentAge),  
  5.     }).then((documentReference) {  
  6.         clearForm();  
  7.     }).catchError((e) {  
  8.         print(e);  
  9.     });  
  10. }  
Delete Student
  1. Future<void> deleteStudent(DocumentSnapshot doc) async {  
  2.    db.collection("students").document(doc.documentID).delete();  
  3.    clearForm();  
  4. }  
List the students using Stream Builder. Stream Builder provides a way to generate stream data in any format you want. You can make a list, grid, card list. Stream Builder has an event listener for any update in stream and it automatically updates the client side.
  1. StreamBuilder < QuerySnapshot > (stream: db.collection("students").snapshots(), builder: (BuildContext context, AsyncSnapshot < QuerySnapshot > snapshot) {  
  2.     if (!snapshot.hasData) return new Text("There is no expense");  
  3.     return Expanded(child: new ListView(children: generateStudentList(snapshot), ), );  
  4. }, ),  
This is how you can perform basic CRUD operations in Firestore.
Please download the attached source code and run it and make tweaks so you will get a better idea of how it works.

Conclusion

 
In this article, we have learned how we setup a Firestore database in Firebase and perform CRUD operations using Flutter.
Author
Parth Patel
259 7k 1.6m
Next » Set App Icon