0

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')));
  }
Ray
  • 3
  • 1

2 Answers2

0

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();
  • Thanks for the answer. I know you can delete a certain document like this, but i want to know how do I loop through all of the documents in a collection and delete exactly those documents, that contain the field value: true. – Ray Jan 29 '23 at 12:01
  • Sorry but i cant i just made this account it says i need 15 reputation. But can you please explain how do I loop through the particular documents to get their document and collection IDs. – Ray Jan 29 '23 at 12:13
0
 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();
});