Home > other >  Limit the number of collection().get()
Limit the number of collection().get()

Time:11-04

The Goal

Limit the number of documents retrieved by FirestpreFirebase.instance.collection().where().get()

What I Did

Currently, the following code retrieves all documents that match the criteria.

FutureBuilder(
  future: FirebaseFirestore.instance
               .collection("users")
               .where('type', arrayContainsAny: _types)
               .get(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        ............
  }

Sure, it seems like it would be easy to fetch all the documents and display only some of them, but this would not only consume unnecessary network but also increase the transmission cost.

For example, can I limit the maximum number of documents I can retrieve to 10?

CodePudding user response:

You can indeed limit the number of results:

FirebaseFirestore.instance
           .collection("users")
           .where('type', arrayContainsAny: _types)
           .limit(10) // <==
           .get(),

Also see the FlutterFire documentation on limiting results and the equivalent Firebase documentation.

  • Related