skip to Main Content

enter image description here

I have these documents, which contain data about each task I add to the list in my app.

child: StreamBuilder(
stream: _tasks.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
if (streamSnapshot.hasData) {
return ListView.builder(
itemCount: streamSnapshot.data!.docs.length,
itemBuilder: (context, index) {
final DocumentSnapshot documentSnapshot =
streamSnapshot.data!.docs[index];
return GestureDetector(
onLongPress: () => _update(documentSnapshot),
child: ListTile(
)
);
},
);
}

return const Center(
child: CircularProgressIndicator(),
);
},
),

I am using a stream builder to build the list. Each of the tasks have a checkmark and when i click it, It updates the value in firestore inside the IsDone field accordingly. I want to click a button outside the stream builder to delete the checked tasks. How do I loop through all the documents and find all the documents that contain the value true and delete them?

I tried this but im doing doing something wrong and it isnt changing anything:

  void _delete() {
    var docs = _tasks.doc().snapshots();
    docs.forEach((doc){
      if(doc.data()==true){
        _tasks.doc(doc.id).delete();
      }
    });
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Text('You have successfully deleted a product')));
  }

2

Answers


  1. You can delete by doing this below:

    1. find the particular document as per your query and get its document and collection ID.
    2. FirebaseFirestore.instance
      .collection("collection_id")
      .doc("doc_id")
      .delete();
    Login or Signup to reply.
  2.  var datas = await FirebaseCalls.firebaseFirestore
        .collection("collection_id")
        .where("status", isEqualTo: true)
        .get();
    datas.docs.forEach((element) {
      FirebaseFirestore.instance
          .collection("collection_id")
          .doc(element.id)
          .delete();
    });
    

    or you can do like this as well.

    var datas =
        await FirebaseCalls.firebaseFirestore.collection("collection_id").get();
    datas.docs
        .where((element) => element["status"] == true)
        .toList()
        .forEach((el) {
      FirebaseFirestore.instance
          .collection("collection_id")
          .doc(el.id)
          .delete();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search