Flutter – 如何创建一个可以无限上下滚动的列表

huangapple go评论79阅读模式
英文:

Flutter - How to create an infinite scrollable list up and down

问题

我想创建一个类似于使用ListView.builder可以实现的无限滚动列表:

ListView.builder(
  itemBuilder: (context, index) => Text(index.toString()),
);

但这样做只会在"一个方向"(向下)创建一个无限列表:index 只能是 0 <= index

我希望还能够向上滚动,这相当于具有可能为负的 index

是否有任何内置小部件可以实现这个功能?我找不到任何东西,即使在 slivers 中也找不到:

英文:

I want to create an infinite scrollable list like it is possible to do with ListView.builder :

ListView.builder(
  itemBuilder: (context, index) =&gt; Text(index.toString()),
);

But doing so only creates an infinite list in "one direction" (down): index can only be 0 &lt;= index.

I would like to also be able to scroll up which would be equivalent to having an index being possibly negative.

Is there any built-in widget for that? I couldn't find anything, even among the slivers:

答案1

得分: 1

我不知道是否这是最流畅的解决方案,但你可以向你的ScrollController添加一个监听器,检查 _controller.position.pixels <= _controller.position.minScrollExtent,然后将你想要添加到ListView.builder列表中的当前索引的数据添加到列表中,然后使用ScrollController跳转到插入数据之前的位置。

为了更容易滚动回到正确的项目,你可以使用scrollable_positioned_list包,就像这里那样。

我没有测试这是否会导致可见的抖动,但也许值得一试。

英文:

I don't know if that's the sleekest solution, but you could add a listener to your ScrollController, check if _controller.position.pixels &lt;= _controller.position.minScrollExtent, then add the data you want to have 'above' the current index to the list of the ListView.builder and then use the ScrollController to jump down to where you were before you inserted the data.

To make it easier to scroll back to the right item you could use the scrollable_positioned_list package like here.

I didn't test if that results in visible jitter or not, but maybe worth a try.

答案2

得分: -1

没有编程语言允许我们使用负索引值。但它们在不同的编程语言中有不同的功能(在Python中,-1表示最后一个对象,-2表示倒数第二个对象)。但是Dart不支持负索引,因此列表也不支持。

我认为您想要做的是将两个“无限”列表/数组组合在一起。我建议您使用两个列表。在两个列表中都使用shrinkWrap: truephysics: const NeverScrollableScrollPhysics(),然后将它们包装在SingleChildScrollView中。

为了能够更好地帮助您,我需要更多的信息。但这应该足够让您开始了。

英文:

No programming language allows us to use a negative index value. But they have different functionalities in different languages (in Python you are refering with -1 to the last object and -2 to the second last). But Dart doesnt support negative indexes, so the lists do not do it either.

I think what you wan to do is to combine two "infinite" Lists/arrays. I would advise you to use two lists. Use
shrinkWrap: true and physics: const NeverScrollableScrollPhysics()
in both lists and Wrap them with SingleChildScrollView.

To give you a better help, I would need more Informations. But this should do it for the start.

huangapple
  • 本文由 发表于 2023年6月5日 11:31:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定