skip to Main Content

I want to delete the whole collection using Flutter. So the entire student section I want to be gone.
I only found deleting single documents… and I don’t want to delete every document manually.
How do I automate that using Flutter.
Something like this: (just so you know how to attempt this)

final firebase = FirebaseFirestore.instance.collection('Students');
await firebase.delete;

Here is an Image of my Firestore Console.

Thanks for any help.

3

Answers


  1. You can delete you collection by using for loop in .then

    FirebaseFirestore.instance.collection('Student').get().then((value) {
         for (DocumentSnapshot students in value.docs){
              students.reference.delete();
           }
         });
    
    Login or Signup to reply.
  2. How do I automate that using Flutter?

    If there is an event that happens that should trigger the deletion of the collection, then I recommend you write a Cloud Function for that. This means that once the event happens, the function is triggered and the collection gets deleted internally.

    @KushalHapani solution will work, however, iterating through all documents within the collection and deleting them in client-side code, will work safely only for small collections of documents. However, if your collection gets larger, it’s recommended to delete the documents in smaller batches to avoid out-of-memory errors.

    Login or Signup to reply.
  3. You can delete a collection by retrieving the documents in the collection, loop through each document and call the delete method on its reference.

    FirebaseFirestore firestore = FirebaseFirestore.instance;
    
    // name of the collection to be deleted
    String collectionName = "Students";
    
    // Get a reference to the collection
    CollectionReference collectionRef = firestore.collection(collectionName);
    
    // Delete the collection
    collectionRef.get().then((snapshot) {
      for (DocumentSnapshot student in snapshot.docs) {
        student.reference.delete();
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search