Firebase pagination in flutter

你离开我真会死。 提交于 2020-07-23 08:04:22

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/59692601/firebase-pagination-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!