简体   繁体   English

如何对flutter中的数据进行分页监听,有效取消不必要的监听?

[英]How to paginate and listen to the data and cancel unnecessary listeners in flutter effectively?

Imagine I am trying to get an infinite scrolling similar to that of Instagram by paginating the post and I will also be listening to the post detail changes for each post that have been queried.想象一下,我正在尝试通过对帖子进行分页来实现类似于 Instagram 的无限滚动,并且我还将监听已查询的每个帖子的帖子详细信息更改。

I start off by querying the first 10 posts:我首先查询前 10 个帖子:

void getPosts(){
postStream =
      firestore.collection('posts')
          .limit(10)
          .orderBy('createdAt', descending: true)
          .snapshots().listen((documentSnapshot) {... code to convert to each doc from JSON..}
}

As the user scrolls down, I detect the scroll with the listener and query for more posts当用户向下滚动时,我使用侦听器检测滚动并查询更多帖子

void getMorePosts(){
paginatedPostStream =
      firestore.collection('posts')
          .limit(10)
          .orderBy('createdAt', descending: true)
          .startAfterDocument(lastPostDocSnapshot)
          .snapshots().listen((documentSnapshot) {... code to convert to each doc from JSON..}
}

When the user no longer needs these post, I'll cancel the stream in the following way:当用户不再需要这些帖子时,我会通过以下方式取消stream:

postStream.cancel();
paginatedPostStream.cancel();

However, I realized that doing so only stopped listening to the earliest and latest paginated stream. For example, the user may have queried in the following way然而,我意识到这样做只是停止监听最早和最新分页的stream。例如,用户可能通过以下方式查询

10 | 10 | 10 | 10 | 10
^                   ^

but the canceling of stream only applies for the first and last 10 posts queried.但取消stream只适用于查询的前10个帖子和后10个帖子。 How can I more effectively cancel the listener to prevent data leakage?如何更有效的取消监听,防止数据泄露?

Any suggestion is welcomed.欢迎任何建议。 Thank you.谢谢你。

As discussed in the comments, you will need to manage all streams instead of just the first and last one.正如评论中所讨论的,您将需要管理所有流,而不仅仅是第一个和最后一个。 If you want to limit the resources being consumed, you will need to close each stream as it becomes obsolete.如果您想限制正在消耗的资源,您将需要关闭每个 stream,因为它变得过时了。

There is no single best practice here, but most implementation I know of, implement a virtual window of few (say 3-5) screens full of information.这里没有单一的最佳实践,但我所知道的大多数实现都是实现一个虚拟的 window,其中有几个(比如 3-5)个充满信息的屏幕。 So if in your case you can display 10 documents on the screen at once, you'd keep listeners on 3-5 streams of 10 documents: the information that is currently displayed and 1 or 2 screenfull's up and down.因此,如果在您的情况下您可以一次在屏幕上显示 10 个文档,那么您将让听众保持在 3-5 个 10 个文档流上:当前显示的信息和 1 或 2 个屏幕的上下。 Any stream outside of this virtual window can then be cancelled to reduce resource consumption.然后可以取消此虚拟 window 之外的任何 stream 以减少资源消耗。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM