How to Delete All Documents In a Collection In FireStore With Flutter ?

· 3 min read
How to Delete All Documents In a Collection In FireStore With Flutter
How to Delete All Documents In a Collection In FireStore With Flutter

Earlier, we have been through question and answer based on Firebase so we will add more things in the Firebase series with this article where we will go through How to Delete All Documents In a Collection In FireStore With Flutter ??

User can also refer to our other articles based on

How to Get Download URL from Firebase In Flutter as well as How to Get Firebase Token In Flutter.

How to Delete All Documents In a Collection In FireStore With Flutter?

FireStore is used to store and retrieve data from one flutter application to and from FireStore. It creates a collection with a specific name specified name and stores all data in it.

As per the official document Firestore docs, there isn’t currently an operation that atomically deletes a collection.

The user will need to get all the documents and loop through them to delete each of them.

Users can give try to below code in a flutter.

firestore.collection('messages').getDocuments().then((snapshot) {
  for (DocumentSnapshot ds in snapshot.documents){
    ds.reference.delete();
  });
});

User can also delete all Documents from firestore collection one by one:

db.collection("users").document(userID).collection("cart")
    .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {                                  
                db.collection("users").document(userID).
                    collection("cart").document(document.getId()).delete();
            }
        } else {
        }
    }
});

As per the latest version of Firebase, users can give try to below code.

_collectionReference.snapshots().forEach((element) {
        for (QueryDocumentSnapshot snapshot in element.docs) {
          snapshot.reference.delete();
        }
      });

Conclusion:

Thanks for being with us on a Flutter Journey!!!

Keep Learning !!! Keep Fluttering !!!

In this article, we have been through How to Delete All Documents In a Collection In FireStore With Flutter?

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply