如何在 flutter listview 中通过索引号滚动到索引?
How to scroll to an index by its index number in flutter listview?
我有一个列表视图。我想通过相应的索引号转到某个小部件。
我试过使用 ScrollController,但它需要偏移值才能跳转到索引。但是我想通过使用它的索引号跳转到一个小部件。
请帮我解决一下
提前致谢。
不幸的是,ListView 没有内置的 scrollToIndex() 函数方法。您必须开发自己的方法来测量 animateTo()
或 jumpTo()
的该元素的偏移量,或者您可以从其他帖子中搜索建议的 solutions/plugins,例如:
(一般的 scrollToIndex 问题自 2017 年起在 flutter/issues/12319 讨论,但目前仍无计划)
但是有一种不同类型的 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 团队开发。)
我有一个列表视图。我想通过相应的索引号转到某个小部件。
我试过使用 ScrollController,但它需要偏移值才能跳转到索引。但是我想通过使用它的索引号跳转到一个小部件。
请帮我解决一下 提前致谢。
不幸的是,ListView 没有内置的 scrollToIndex() 函数方法。您必须开发自己的方法来测量 animateTo()
或 jumpTo()
的该元素的偏移量,或者您可以从其他帖子中搜索建议的 solutions/plugins,例如:
(一般的 scrollToIndex 问题自 2017 年起在 flutter/issues/12319 讨论,但目前仍无计划)
但是有一种不同类型的 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 团队开发。)