【问题标题】:How to load more at the top of the screen in Flutter?如何在 Flutter 的屏幕顶部加载更多内容?
【发布时间】:2020-01-05 02:13:07
【问题描述】:

如何将屏幕顶部的更多项目加载到 ListView 小部件中,并从加载更多项目之前的位置继续滚动?

我知道如何检测 ListView 的底部或列表的顶部。像这样:

_scrollListener() {
    if (_controller.offset >= _controller.position.maxScrollExtent &&
        !_controller.position.outOfRange) {
      setState(() {
        // reach the bottom - load more items
      });
    }
    if (_controller.offset <= _controller.position.minScrollExtent &&
        !_controller.position.outOfRange) {
      setState(() {
        //reach the top - load more items
      });
    }
  }

所以,当我在列表底部加载数据时,新项目只是附加到现有列表中,看起来很自然,因为用户可以继续向下滚动而不会出现任何问题。

问题是:当我更新项目列表时,滚动从屏幕顶部(0 像素位置)开始,而不是从我在加载更多项目之前的项目位置开始。

我试过的:我试过计算加载项的高度,然后跳转到以像素为单位的计算范围,但效果不佳,因为元素的大小在我的 ListView 中可以是动态的,这会计算出我必须滚动的错误像素数。

问题如下:如何在将项目加载到列表开头时实现相同的 ListView 行为?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您也许可以使用类似于此处描述的方法:https://github.com/flutter/flutter/issues/12319#issuecomment-488170337

    这样写:

          CustomScrollView(center: aKey, slivers: [
            SliverList(
              delegate: SliverChildListDelegate(
                [...new items...].reversed.toList(),  
              ),
            ),
            SliverList(
              key: aKey,
              delegate: SliverChildListDelegate(
                [...old items...],
              ),
            ),
          ]);
    

    您可以在有意义的情况下使用代表类型。然后滚动偏移量为 0 应该将旧的第一项放在顶部。

    【讨论】:

    • 当需要在底部重新加载时,使用CustomScrollView的anchor属性可能会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 2022-11-02
    • 2018-08-28
    • 2018-04-10
    • 2020-10-18
    • 2010-09-19
    相关资源
    最近更新 更多