0

im making some kind of notes app, and i want to implement a feature that can trigger field in all document. For example, all documents will have a field 'isDone' and when the user presses the clear all button, the field 'isDone' in all documents will change to true.

i am using Stream Builder and Staggered Gridview to display all data from fire store, and i want to put logic to convert all that data into void method.

Here's the code I've simplified:

class Notes extends StatefulWidget {
  @override
  _NotesState createState() => _NotesState();
}

class _NotesState extends State<Notes> {
  var collection = FirebaseFirestore.instance.collection('notes');

  void makeAllDocsDone() {
    // logic here
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.clear),
        onPressed: () {
          makeAllDocsDone();
        },
      ),
      body: StreamBuilder(
        stream: FirebaseFirestore.instance.collection('notes').snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (!snapshot.hasData) return const SizedBox.shrink();
          return Container(
            padding: EdgeInsets.symmetric(horizontal: 10),
            child: StaggeredGridView.countBuilder(
              crossAxisCount: 30,
              mainAxisSpacing: 10,
              crossAxisSpacing: 10,
              itemCount: snapshot.data!.docs.length,
              itemBuilder: (context, index) {
                return InkWell(
                  child: Container(
                    color: Colors.red,
                    child: Column(
                      children: [
                        Text(snapshot.data!.docs[index]['title']),
                        TextButton(
                          child: Text('DONE'),
                          onPressed: () {
                            // This only change selected docs
                            snapshot.data!.docs[index].reference.update({
                              'isDone': 'true',
                            });
                          },
                        ),
                      ],
                    ),
                  ),
                );
              },
              staggeredTileBuilder: (index) {
                return StaggeredTile.count(15, 15);
              },
            ),
          );
        },
      ),
    );
  }
}


  • Have you checked [How to update a single field of all documents in Firestore using Flutter](https://stackoverflow.com/questions/63321875/how-to-update-a-single-field-of-all-documents-in-firestore-using-flutter) ? – Dharmaraj Aug 24 '21 at 05:30
  • Firestore has no SQL-like "update where" command. You will have to query for the documents you want to update, iterate the results, update each document individually. – Doug Stevenson Aug 24 '21 at 06:33

0 Answers0