[Solved] is .limit() Method from Firstore is smart enough to detect new data limit depends on the changing int variable


Asked by Jack on January 07, 2022 (source).

i have StatefulWidget which contains Future.Bulder Widget and listener controller method in Listview.builder like so

class Messages extends StatefulWidget {

  const Messages({Key? key,}) : super(key: key);

  _MessagesState createState() => _MessagesState();

class _MessagesState extends State<Messages> {

  int limit = 10 ;

  void initState() {

    if (controller!.offset >= controller!.position.maxScrollExtent && !controller!.position.outOfRange) {
      setState(() {
        limit = limit+10;

  Widget build(BuildContext context) {

    return Scaffold(

        body: FutureBuilder(
        future: FirebaseFirestore.instance.collection("users").limit(limit).get(),
    builder: (context , AsyncSnapshot<QuerySnapshot> messages ) {
    if (!messages.hasData) {
    return Center(
    child: circulearProgress(),);
    return ListView.builder(
    controller: controller,
    itemCount: messages.data!.docs.length ,
    itemBuilder: (context , int index){

    DocumentSnapshot documentSnapshot = messages.data!.docs [index] ;

    return Text(documentSnapshot['textMessage']);

ok now .get() will get 10 docs as a default also i handle the listener to increase 10 to limit variable once the user scroll to down page then stream get other 10 docs besides the previous old 10 docs .. Now the question is

Will .get() read only the new 10 docs in every time that user scroll down or will it read again the old previous 10 docs with new 10 ones ??
if not how can avoid to read the old docs again in the same my example ..

any edit to my code with solution sample will be thankful ..

best regards


Question answered by Prabir (source).

To answer your question -

Will .get() read only the new 10 docs every time that user scrolls down OR will it read again the old previous 10 docs with new 10 ones?

Yes, it will read the previous docs and the new 10 docs. Here you are increasing the limit and fetching the data based on the new limit, so it will fetch the number of documents that is specified in the limit() method. So each time the limit is increased it will fetch the previous set of documents along with the new 10 documents.

If you want to get pagination like, fetch the first 10 documents and then fetch only the next 10 sets of documents, then I would suggest you to use the limit method with the startAfterDocument method and pass an existing document as the startAfterDocument parameter. You can find more about limiting and using startAfterDocument here.

To get a detailed description of pagination in Firestore you can go through this video.