Member-only story

Flutter: How to get a Count of Documents in a Firestore Collection.

Michael Cockinos
2 min readFeb 22, 2023

In Flutter, you can use StreamBuilder to create a widget that automatically updates its content based on a stream of data. If you want to use collection.get.count() to get the count of documents in a Firestore collection, you can do the following:

In this example, snapshots() returns a stream of query snapshots representing the data at a particular point in time. We then use map() to convert each snapshot to its size property, which represents the number of documents in the snapshot.
Use StreamBuilder to build your widget and display the count:

Create your variables, one as Query and the other as Stream<int>:

Query newUserQuery;
Stream<int> newUserCountStream;

The initialize the variables in initState(). You can build your query here with the where and orderBy clause.
In the below example, I’m looking for a count of new members.

  @override
void initState() {
// TODO: implement initState
super.initState();
...

newUserQuery = userRef
.where('isNewMember', isEqualTo: true);

newUserCountStream =
newUserQuery.snapshots().map((snapshot) => snapshot.size);
...
}

Then in a StreamBuilder Widget:

    StreamBuilder<int>(
stream: newUserCountStream,
builder: (context, snapshot) {
if (snapshot.hasData) {
var newMembers = snapshot.data…

--

--

Michael Cockinos
Michael Cockinos

Written by Michael Cockinos

In the It industry since 2000. Code in ASP, HTML, dart flutter and loads of other flavours... Host websites, redhot.com.au

No responses yet