Abdelbaki Boukerche
Abdelbaki Boukerche

Reputation: 1692

Firebase pagination in flutter

i'm using Firebase firestore for an app i'm working on. Basically, i have a Collection('Chat') that may contain thousand of documents i need a way to implement firebase pagination to limit how much document is retrieved from the backend.

im using streamBuilder and passing the Query below as stream :

stream: widget.messageDocRef
      .collection('Chat').orderBy('timestamp', descending: true)
      .limit(80)
      .snapshots();

i have a ListView and a scrollController for it, code:

ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        reverse: true,
        controller: _scrollController,
        padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 10.0),
        children: messagesBubble,
      ),

i couldn't find any good documentation on how to implement it in flutter.

Thanks!

Upvotes: 2

Views: 3838

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

Using a ScrollController, then inside the initState do the following :

@override
  void initState() {
    this.getdbData();
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        getdbData();
      }
    });
  }

So first add a listener that will register a closure to be called when the object changes. Then check if position.pixel is equal to the position.maxScrollExtent and call the method if the above is satisfied.

Also don't forget to dispose the controller:

@override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

https://api.flutter.dev/flutter/widgets/ScrollPosition-class.html

https://api.flutter.dev/flutter/widgets/ScrollController-class.html

The getdbData() is the method that will retrieve the data from the database which you will assign to the property stream

Upvotes: 3

Related Questions