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.

dependencies:  
flutter:  
sdk: flutter  
cupertino_icons: ^0.1.2  
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,

    import 'package:cloud_firestore/cloud_firestore.dart';  

Initialize the Firebase instance.

final db = Firestore.instance; 

To add a new student in students collection (we have created in Firestore).

    Future < void > addStudent() async {  
        await db.collection("students").add({  
            'name': _studentName,  
            'age': int.parse(_studentAge),  
        }).then((documentReference) {  
            print(documentReference.documentID);  
            clearForm();  
        }).catchError((e) {  
            print(e);  
        });  
    }  

Edit student information

    Future < void > editStudent() async {  
        await db.collection("students").document(docIdToUpdate).updateData({  
            'name': _studentName,  
            'age': int.parse(_studentAge),  
        }).then((documentReference) {  
            clearForm();  
        }).catchError((e) {  
            print(e);  
        });  
    }  

Delete Student

Future<void> deleteStudent(DocumentSnapshot doc) async {  
   db.collection("students").document(doc.documentID).delete();  
   clearForm();  
} 

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.

    StreamBuilder < QuerySnapshot > (stream: db.collection("students").snapshots(), builder: (BuildContext context, AsyncSnapshot < QuerySnapshot > snapshot) {  
        if (!snapshot.hasData) return new Text("There is no expense");  
        return Expanded(child: new ListView(children: generateStudentList(snapshot), ), );  
    }, ),  

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.

#flutter #firebase #mobile-apps

Firestore CRUD Operation in Flutter
29.85 GEEK