Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting document from cloud_firestore in flutter

I am returning a streamBuilder and inside the streamBuider, it returns a widget.
Now I have wrap a widget with dismissible so that I can delete the document from the collection from the cloud_firestore.

showingTheSelectedDateEvents() {
    List<Widget> listViewContainer = [];

    return StreamBuilder<QuerySnapshot>(
      stream: firestoreInstance.collection('eventDetails').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(
              backgroundColor: Colors.lightBlueAccent,
            ),
          );
        }
        String theDatabaseDate;
        final allDocuments = snapshot.data.docs;
        //here we get all the documents from the snapshot.
        for (var i in allDocuments) {
          theDatabaseDate = i.data()['dateTime'];
          if (theDatabaseDate == theDataProvider.databaseSelectedDate) {
            print(theDatabaseDate +
                " is same as " +
                theDataProvider.databaseSelectedDate);
            listViewContainer.add(Dismissible(
              key: ObjectKey(snapshot.data.docs.elementAt(0)),
              onDismissed: (direction) {
                firestoreInstance
                    .collection("eventDetails")
                    .doc()
                    .delete()
                    .then((_) {
                  print("success!");
                });
              },
             child://here
          
            ));
            print(listViewContainer.length);
          } else {
            print("no any events for today");
          }
        }
        return Expanded(
          child: ListView(
            reverse: true,
            padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
            children: listViewContainer,
          ),
        );
      },
    );
  }

I tried this for deleting the data from the cloud_firestore

key: ObjectKey(snapshot.data.docs.elementAt(0)),
onDismissed: (direction) {
                firestoreInstance
                    .collection("eventDetails")
                    .doc()
                    .delete()
                    .then((_) {
                  print("success!");
                });
              },           

I want to delete the specific document from the collection
I cannot figure out how to do that.
here is the database model
enter image description here

I am trying to delete the document of eventDetails collection.

like image 949
Aman Chaudhary Avatar asked Sep 15 '20 07:09

Aman Chaudhary


People also ask

How do I delete a document in firestore Flutter?

Deleting a Firestore document is a straightforward thing. We just have to point to a doc and call delete on it. final _db = FirebaseFirestore. instance; await _db.

How do I delete files from Firebase storage?

To delete a file, first create a reference to that file. Then call the delete() method on that reference, which returns a Promise that resolves, or an error if the Promise rejects.

How do I delete a collection on firestore?

To delete an entire collection or subcollection in Cloud Firestore, retrieve all the documents within the collection or subcollection and delete them. If you have larger collections, you may want to delete the documents in smaller batches to avoid out-of-memory errors.

How to delete all documents from FireStore collection in flutter?

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. User can also delete all Documents from firestore collection one by one:

How do I delete documents with Cloud Firestore?

To delete documents with Cloud Firestore, you can use the delete method on a DocumentReference: If you need to remove specific properties from within a document rather than the document itself, you can use the delete method with the FieldValue class:

How do I use Cloud Firestore in flutter?

To start using the Cloud Firestore package within your project, import it at the top of your project files: Before using Firestore, you must first have ensured you have initialized FlutterFire.

How to delete a document in Firebase FireStore?

Deleting a Firestore document is a straightforward thing. We just have to point to a doc and call delete on it. final _db = FirebaseFirestore.instance; await _db.collection("notes").doc("note1").delete(); That’s it. The pointed document will be deleted by the above function.


2 Answers

doc() will generate a new random id, therefore if you don't have access to the id, then you need to do the following:

    FirebaseFirestore.instance
        .collection("eventDetails")
        .where("chapterNumber", isEqualTo : "121 ")
        .get().then((value){
          value.docs.forEach((element) {
           FirebaseFirestore.instance.collection("eventDetails").doc(element.id).delete().then((value){
             print("Success!");
           });
          });
        });

Use a where() condition to get the required document and delete it.


Since in your code you are using:

return StreamBuilder<QuerySnapshot>(
      stream: firestoreInstance.collection('eventDetails').snapshots(),

Here you are fetching all the documents under eventDetails, therefore you can add a unique field to the document and then inside the for loop you can get the id:

for (var i in allDocuments) {
          if(i.data()["subject"] == "Mathemtics")
               docId = i.id;

And then you can delete it:

              onDismissed: (direction) {
                FirebaseFirestore.instance
                    .collection("eventDetails")
                    .doc(docId)
                    .delete()
                    .then((_) {
                  print("success!");
                });
              },

This way you dont need to fetch the documents twice.

like image 182
Peter Haddad Avatar answered Nov 10 '22 06:11

Peter Haddad


You can always query the document to get the document ID and perform the deletion.

var collection = FirebaseFirestore.instance.collection('users');
var snapshot = await collection.where('age', isGreaterThan: 20).get();
for (var doc in snapshot.docs) {
 await doc.reference.delete();
}

To delete all the documents, iterate through the QueryDocumentSnapshot.

var collection = FirebaseFirestore.instance.collection('collection');
var querySnapshots = await collection.get();
for (var doc in querySnapshots.docs) {
  await doc.reference.delete();
}
like image 33
CopsOnRoad Avatar answered Nov 10 '22 07:11

CopsOnRoad