【问题标题】:Using Streams in flutter在 Flutter 中使用 Streams
【发布时间】:2021-04-05 15:53:15
【问题描述】:

我正在开发聊天应用程序,我正在尝试使用分页从 firestore 中检索有限数量的数据,并在用户继续滚动时检索其余数据,我还想监听数据库中的最新更改并显示它给用户。我尝试通过在构造函数中创建一个包含快照侦听器的 Stream 类并将任何新更改添加到流控制器来做到这一点,它还有一个检索分页数据并在用户滚动时将其添加到流控制器的方法。问题是当从数据库中检索数据并将其添加到流控制器时,它会替换以前的数据而不是添加到它。下面是我创建的类

class ChatStream {
  final String messageId;
  final _controller = StreamController<QuerySnapshot>();
  var _snapshots;
  
  ChatStream({this.messageId}) {
    _snapshots = FirebaseFirestore.instance
        .collection("chats")
        .doc(messageId)
        .collection("messages")
        .orderBy("time", descending: false)
        .limitToLast(10)
        .snapshots();

    _snapshots.listen((onData) {
      _controller.sink.add(onData);
    });
  }
  getChats(DocumentSnapshot lastDocument) async {
    FirebaseFirestore.instance
        .collection("chats")
        .doc(messageId)
        .collection("messages")
        .orderBy("time", descending: false)
        .endBeforeDocument(lastDocument)
        .limitToLast(100)
        .snapshots()
        .forEach((action) {
      _controller.sink.add(action);
    });
  }

  Stream get stream {
    return _controller.stream;
  }
}

我创建了一个名为 c 的 ChatStream 类型的对象,然后我使用 c.stream 获取流以在流构建器中使用,然后我在 initState 方法中使用滚动侦听器调用 getChats 方法,就像这样

 _scrollController.addListener(() {
      double maxScroll = _scrollController.position.minScrollExtent;
      double currentScroll = _scrollController.position.pixels;
      double delta = MediaQuery.of(context).size.height * 0.20;
      if (maxScroll == currentScroll) {
     
      c.getChats(lastDocument);
      }


    });

【问题讨论】:

  • Firestore API 根本无法轻松地同时执行分页和获取实时更新。如果你想正确地做到这一点,你将不得不花费大量精力分别为每个数据页面添加侦听器,并处理查询结果更改位置时的所有边缘情况。
  • 哦,好吧,这听起来很复杂,但谢谢

标签: flutter google-cloud-firestore stream chat stream-builder


【解决方案1】:

Firestore API 根本无法轻松同时执行分页和获取实时更新。如果你想正确地做到这一点,你将不得不花费大量精力分别为每个数据页面添加侦听器,并处理查询结果更改位置时的所有边缘情况

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 2018-11-28
    • 2019-10-22
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2020-05-26
    相关资源
    最近更新 更多