如何在flutter listview中按索引号滚动到索引?

Md.*_*afi 3 flutter flutter-listview

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

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

请帮我修复它提前谢谢。

TWL*_*TWL 8

不幸的是,ListView 没有针对 scrollToIndex() 函数的内置方法。您必须开发自己的方法来测量animateTo()or 的该元素的偏移量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));
Run Code Online (Sandbox Code Playgroud)

(请注意,这个库是由 Google 开发的,而不是由 Flutter 核心团队开发的。)