Rajendra A Verma
Rajendra A Verma

Reputation: 413

How to Count the number of document in a particular collection in firestore flutter and display at Scaffold Text widget

I want to display the no. of documents in collection in Realtime.[In image 4 document][1] [1]: https://i.sstatic.net/VLiDy.jpg

 countDocuments() async {
    QuerySnapshot _myDoc = await collectionReference.get();
    List myDocCount = _myDoc.docs;
    var totalStudent = myDocCount.length.toString();
    return print(totalStudent);
  }

In above code when I called countDocument() function in raised button or any button type it print the total document present in collection in DEBUG CONSOLE of VS code BUT I want to display this No. in inside of Scaffold's Text() widget. So, how I Can display.

Upvotes: 2

Views: 864

Answers (2)

Victor Eronmosele
Victor Eronmosele

Reputation: 7686

Since this is an async operation, you can use a FutureBuilder to wrap the Text widget and use it in the Scaffold.

     FutureBuilder(
        future: collectionReference.get(),
        builder: (context, snapshot) {
           if (snapshot.hasData) {
             List myDocCount = snapshot.data.docs;
             var totalStudent = myDocCount.length.toString();
             return Text(totalStudent.toString());
           } else {
             return Center(child: CircularProgressIndicator());
           }
        },
      );

Upvotes: 1

Muhammad Arbaz Zafar
Muhammad Arbaz Zafar

Reputation: 661

simply you can do like that text:Text("${totalStudent}"),

Upvotes: 0

Related Questions