Flutter Firestore

In this article, we will add Cloud Firestore to a Flutter application, perform different read, write operation and use some queries to retrieve data.

You can Download Source Code via Github.

Get Started With Cloud Firestore

  1. Create Project on https://console.firebase.google.com/
  2. Add App in Firebase console (Android and iOS)
  3. Download google-service.json file and Add in Android folder
  4. Download GoogleService-Info.plist file and Add in iOS folder

Add plugin in pubspace.yaml file

firebase_core: ^1.6.0
cloud_firestore: ^2.5.3

Initialization of Firebase

await Firebase.initializeApp(); in main.dart file

Adding Data To Firestore

Cloud Firestore will generate a random id, let us see. So first in your State class you need to get an instance of Cloud Firestore:

final firestoreInstance = FirebaseFirestore.instance;

Now, you can add the data:

firestoreInstance.collection("users").add(
          {
            "name" : "sumeet patel",
            "age" : 29,
            "email" : "[email protected]",
            "password" : "test123",
          }).then((value){
        print(value.id);
      });

After adding this data you can see in Firebase like below

Update Data In Firestore

For update data in Firebase we will use firebase generated document id. Here we will update age for this user.

firestoreInstance.collection("users").doc([YOUR DOCUMENT ID]).update(
        {
          "name" :"sumeet patel",
          "age" : 30,
          "email" : "[email protected]",
          "password" : "test123",
        }).then((value){
      print("success!");
    });

After update this data you can see in Firebase like below

Adding SubCollection In Flutter

We can also add sub collection in user data. For eg. If we want to add Hobby in particular user collection then we need to add sub collection in data like this…

firestoreInstance.collection("users").add({
    "name" :"sumeet patel",
    "age" : 30,
    "email" : "[email protected]",
    "password" : "test123",
  }).then((value) {
    print(value.id);
    firestoreInstance
        .collection("users")
        .doc(value.id)
        .collection("hobby")
        .add({"hobbyName": "reading", "hobbyType": "Novel"});
  });

Delete Data From Firestore

To delete data from a document, you can use the method delete() which returns a Future<void>:

firestoreInstance.collection("users").doc([YOUR DOCUMENT ID]).delete().then((_) {
     print("success!");
    });

Retrieving Data From Firestore

To retrieve data from Cloud Firestore, you can either listen for realtime updates or you can use the method get():

firestoreInstance.collection("users").get().then((querySnapshot) {
    querySnapshot.docs.forEach((result) {
      print(result.data());
    });
  });

Retrieve SubCollection

So, as you can see above we didn’t retrieve data from the hobby collection since queries are shallow, therefore to retrieve the data from subcollections, you can do the following:

firestoreInstance.collection("users").get().then((querySnapshot) {
  querySnapshot.docs.forEach((result) {
    firestoreInstance
        .collection("users")
        .doc(result.id)
        .collection("hobby")
        .get()
        .then((querySnapshot) {
      querySnapshot.docs.forEach((result) {
        print(result.data());
      });
    });
  });
});

Listen For Realtime Updates

To constantly listen for changes inside a collection, you can use the method snapshots():

firestoreInstance.collection("users").snapshots().listen((result) {
      result.docChanges.forEach((res) {
        if (res.type == DocumentChangeType.added) {
          print("added");
          setState(() {
           //You can update your view here...
          });
        } else if (res.type == DocumentChangeType.modified) {
          print("modified");
          setState(() {
            //You can update your view here...
          });
        } else if (res.type == DocumentChangeType.removed) {
          print("removed");
        }
      });
    });

Perform Queries In Firestore

Cloud Firestore uses index to improve the performance of retrieving the data from the database. If there is no index then the database must go through each collection to retrieve the data which will make the performance bad. There are two index type single index which are automatically indexed by Firestore and composite index which you need to manually create. Therefore, you have to create an index whenever you are using more than one where() in a single query or if you are using one where() and orderBy() so basically when it is two different fields.

firestoreInstance
        .collection("users")
        .where('age', isLessThan: 45)
        .get()
        .then((querySnapshot) {
      setState(() {
        querySnapshot.docs.forEach((result) {
          //You can update your view here...
        });
      });

You can Download Source Code via Github.

Leave a Reply

Your email address will not be published.