Home > Blockchain >  How to get the number of elements in a firebase collection?
How to get the number of elements in a firebase collection?

Time:02-17

Im trying to get the sum of elements in my firebase collection so far ive tried doing

final int documents = await FirebaseFirestore.instance.collection('stations').snapshots().length;

but when i print documents variable with a print statement i get this:

Instance of '_Future<int>'

What should i do ?

CodePudding user response:

The snapshots property is a stream, and you can't use await on that. Furthermore, you are now essentially awaiting the length property lookup, instead of the asynchronous call.

This should work better:

var docs = await FirebaseFirestore.instance.collection('stations').get();
final int count = docs.length;

The main differences:

  • This uses get instead of snapshots to get the documents.
  • Since get returns a Future, it uses await on that call.
  • Related