【问题标题】:Create infinite scrolling pagination in flutter with FirebaseAnimatedList使用 FirebaseAnimatedList 在颤动中创建无限滚动分页
【发布时间】:2022-11-11 12:59:08
【问题描述】:

当使用FirebaseAnimatedList 在颤动中呈现消息小部件列表时,我将如何实现无限滚动机制,当用户向上滚动时将加载 10 条新消息?这是FirebaseAnimatedList 的代码,下面是我尝试使用的一些方法

    FirebaseAnimatedList(
      shrinkWrap: true,
      physics: const BouncingScrollPhysics(),
      controller: _scrollController,
      query: FirebaseDatabase.instance
          .ref("messages/${widget.placeID}/")
          .orderByChild("timeStamp"),
      itemBuilder: (context, snapshot, animation, index) {
        final json = snapshot.value as Map<dynamic, dynamic>;
        final message = Message.fromJson(json);
        return MessageWidget(
          message: message.text,
          id: message.uid,
          name: message.name,
          lastSender: message.lastSender,
          date: message.timeStamp,
        );
      },
    );
  }

initState 中的代码:

  int scrollValue = 20;
  var messagesQuery;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    setState(() {
      _scrollController.hasClients == true;
      messagesQuery = FirebaseDatabase.instance
          .ref("messages/ChIJu9mKv73Bt4kRu9BSvbTPfDU/")
          .orderByChild("timeStamp")
          .limitToLast(scrollValue);
    });
    _tabController = TabController(length: 3, vsync: this);
    _scrollController.addListener(() {
      if (_scrollController.position.atEdge) {
        bool isTop = _scrollController.position.pixels == 0;
        if (isTop) {
          setState(() {
            scrollValue = 20;
            messagesQuery = FirebaseDatabase.instance
                .ref("messages/ChIJu9mKv73Bt4kRu9BSvbTPfDU/")
                .orderByChild("timeStamp")
                .limitToLast(scrollValue + 10);
          });
        } else {
          print('At the bottom');
        }
      }
    });
    super.initState();
  }

上面的代码没有再添加 20 条消息,没有任何反应。我知道它会检测到列表何时滚动到顶部,因为它输出正确的print 消息,但它没有更新列表以包含更多消息。

【问题讨论】:

  • 在您的滚动控制器侦听器中,您只运行一个查询以返回最后 30 个项目。您想要做的是全局更新滚动值,因为它一遍又一遍地运行相同的查询。如果你做类似 scrollvalue += 20 的事情会发生什么?
  • 当我让滚动容器 += 20 时没有任何反应。我认为问题是更新查询可能不会在下次加载之前更新结果

标签: flutter firebase api firebase-realtime-database google-cloud-firestore


【解决方案1】:

实现无限滚动工作背后的基本思想可以概括为有两个单独的查询:
(1) 查询第一批(不带startAfter)
(2) 用于加载更多内容的查询(完全相同的查询,但使用 startAfter())

您实际上可以查看 this 快速指南,了解使用 Firebase 进行无限滚动。 Infinite Scroll Pagination 有一个有用的文档。

Stackoverflow 中的类似问题:
[3]:How to implement Infinite Scrolling with the new Firebase (2016)?
[4]:Firestore limit using react-infinite-scroll-component only scroll with the given limit
[5]:Firebase infinite scroll proper solution?
[6]:How would I paginate Firestore data with cloud functions?

【讨论】:

    猜你喜欢
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 2021-05-13
    相关资源
    最近更新 更多