【问题标题】:How to scroll to an index by its index number in flutter listview?如何通过颤动列表视图中的索引号滚动到索引?
【发布时间】:2019-12-24 00:05:07
【问题描述】:

我有一个列表视图。我想通过它对应的索引号转到某个小部件。

我尝试过使用 ScrollController,但它需要偏移值才能跳转到索引。但是我想通过使用它的索引号来跳转到一个小部件。

请帮我解决它 提前致谢。

【问题讨论】:

标签: flutter flutter-listview


【解决方案1】:

不幸的是,ListView 没有内置的 scrollToIndex() 函数方法。您必须开发自己的方法来测量该元素对 animateTo()jumpTo() 的偏移量,或者您可以从其他帖子中搜索建议的解决方案/插件,例如:

(自 2017 年以来,flutter/issues/12319 讨论了一般的 scrollToIndex 问题,但目前还没有计划)


但是有一种不同的 ListView 确实支持 scrollToIndex:

您的设置与 ListView 完全相同,并且工作方式相同,只是您现在可以访问 ItemScrollController

  • jumpTo({index, alignment})
  • scrollTo({index, alignment, duration, curve})

简化示例:

ItemScrollController _scrollController = ItemScrollController();

ScrollablePositionedList.builder(
  itemScrollController: _scrollController,
  itemCount: _myList.length,
  itemBuilder: (context, index) {
    return _myList[index];
  },
)

_scrollController.scrollTo(index: 150, duration: Duration(seconds: 1));

(请注意,此库由 Google 开发,而非 Flutter 核心团队开发。)

【讨论】:

  • 很棒的答案。虽然我注意到当index == item.length - 1 时,scrollController 的行为很有趣。也许是因为我使用的是BouncingScrollPhysics()
  • shrinkWrap 不在此插件中
猜你喜欢
  • 2020-12-13
  • 2019-05-31
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 2020-12-10
  • 1970-01-01
  • 2019-04-25
  • 2022-06-12
相关资源
最近更新 更多