Flutter和Firebase streamBuilder分页

时间:2020-01-24 14:02:54

标签: firebase flutter pagination google-cloud-firestore

所以我一直在寻找一种在我的应用程序“ 聊天”中添加分页的方法,但是仍然没有运气:(

这是我的代码

Widget build(BuildContext context) {
return StreamBuilder(
  //TODO add pagination later...

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

  builder: (BuildContext context, AsyncSnapshot snapshot) {
    if (!snapshot.hasData) {
      return Center(
        child: circularProgress(),
      );
    }
    final messages = snapshot.data.documents;
    for (int i = 0; i < snapshot.data.documents.length; i++) {
      DocumentSnapshot doc = snapshot.data.documents.elementAt(i);
      print(doc.metadata.isFromCache
          ? "DATA FROM CACHE"
          : "DATA FROM INTERNET");
    }

    List<MessageBubble> messagesBubble = [];
    for (var message in messages) {
      final docId = message.documentID;

      final messageText = message.data['content'];

      final messageSender = message.data['from'];

      final messageType = message.data['type'];

      final messageBubble = MessageBubble(
        messageDocRef: widget.messageDocRef,
        docId: docId,
        type: messageType,
        text: messageText,
        isMe: widget.currentUser.id == messageSender,
      );
      messagesBubble.add(messageBubble);
    }
    return Expanded(
      child: ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        reverse: true,
        controller: this._scrollController,
        padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 10.0),
        children: messagesBubble,
      ),
    );
  },
);}

我的初始化状态

void initState() {
super.initState();
_scrollController.addListener(() {
  double maxScroll = _scrollController.position.maxScrollExtent;
  double currentScroll = _scrollController.position.pixels;
  if (maxScroll == currentScroll) {
    print("get more products");
  }
});}

MessageBubble 是一个类,用于在单独的气泡中显示每个消息。

直到现在一切都运转良好!但是我需要实现分页并且不丢失 streamBuilder实时更新(“显示新消息”,“删除已删除的消息” ...等)。

我从字面上不知道我将如何实现这一目标,我尝试使用多个查询仍然没有运气。

我希望用户向上滚动时能够看到旧消息,并且在滚动时可以看到较新消息

帮助!!!

2 个答案:

答案 0 :(得分:1)

您尝试过这个method还是这个one吗?

不要限制文档,使其可变并可以每次更新。

答案 1 :(得分:0)

让您的信息流像这样...

int _limit = 20;
...
stream: widget.messageDocRef
      .collection("Chat")
      .orderBy('timestamp', descending: true)
      .limit(_limit)
      .snapshots(),

然后将此侦听器添加到您的scrollController中:

final ScrollController _scrollController = new ScrollController();
...
void initState() {
   _scrollController.addListener(_scrollListener);
}
...
void _scrollListener() {
  if (_scrollController.offset >= _scrollController.position.maxScrollExtent &&
      !_scrollController.position.outOfRange) {
    print("at the end of list");
    setState(() {
        _limit +=20;
    });
  }
}

...
ListView(
   ...
   controller: _scrollController
   ...
)

我仍然不知道如何在屏幕末尾放置进度指示器,但这是我能想到的最好的解决方法。