Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of Firestore documents in flutter

I am building a flutter app and using Cloud Firestore. I want to get the number of all documents in the database.

I tried

Firestore.instance.collection('products').toString().length

but it didn't work.

like image 293
aaww223 Avatar asked Nov 17 '18 15:11

aaww223


4 Answers

Firebase doesn't officially give any function to retrieve the number of documents in a collection, instead you can get all the documents of the collection and get the length of it..

There are two ways:

1)

final int documents = await Firestore.instance.collection('products').snapshots().length;

This returns a value of int. But, if you don't use await, it returns a Future.

2)

final QuerySnapshot qSnap = await Firestore.instance.collection('products').getDocuments();
final int documents = qSnap.documents.length;

This returns a value of int.

However, these both methods gets all the documents in the collection and counts it.

Thank you

like image 155
Mithun Kartick Avatar answered Oct 09 '22 22:10

Mithun Kartick


It Should Be - Firestore.instance.collection('products').snapshots().length.toString();

like image 21
anmol.majhail Avatar answered Oct 09 '22 22:10

anmol.majhail


First, you have to get all the documents from that collection, then you can get the length of all the documents by document List. The below could should get the job done.

Firestore.instance.collection('products').getDocuments.then((myDocuments){
 print("${myDocuments.documents.length}");
});
like image 31
sanjay Avatar answered Oct 10 '22 00:10

sanjay


Since you are waiting on a future, this must be place within an async function

QuerySnapshot productCollection = await 
Firestore.instance.collection('products').get();
int productCount = productCollection.size();

Amount of documents in the collection

like image 37
MItch Avatar answered Oct 09 '22 23:10

MItch