不幸的是,ListView没有对scrollToIndex()函数的内置方法。您必须开发自己的方法来测量animateTo()
或的元素偏移量jumpTo()
,或者可以从其他帖子中搜索建议的解决方案/插件,例如:
自2017年以来, 在flutter / issues / 12319上讨论了一般的scrollToIndex问题,但目前尚无计划)
但是还有另一种不支持scrollToIndex的ListView:
您可以像设置ListView一样进行设置,并且工作原理相同,除了现在可以访问执行以下操作的ItemScrollController之外:
简化示例:
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核心团队开发的。)