How to scroll to an index by its index number in flutter listview?

删除回忆录丶 提交于 2020-08-03 09:08:34

问题


I have a listview . I want to go to a certain widget by it's corresponding index number.

I've tried with ScrollController, but it need offset value to jumpTo the index. But I want to jumpTo a widget by using its index number.

Please, help me to fix it Thanks in advance.


回答1:


Unfortunately, ListView has no built-in approach to a scrollToIndex() function. You’ll have to develop your own way to measure to that element’s offset for animateTo() or jumpTo(), or you can search through suggested solutions/plugins from other posts such as:

  • flutter ListView scroll to index not available
  • Flutter: Scrolling to a widget in ListView

(the general scrollToIndex issue is discussed at flutter/issues/12319 since 2017, but still with no current plans)


But there is a different kind of ListView that does support scrollToIndex:

  • ScrollablePositionedList
    • scrollable_positioned_list
    • dependency: flutter_widgets

You set it up exactly like ListView and works the same, except you now have access to a ItemScrollController that does:

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

Simplified example:

ItemScrollController _scrollController = ItemScrollController();

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

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

(note that this library is developed by Google but not by the core Flutter team.)



来源:https://stackoverflow.com/questions/57545392/how-to-scroll-to-an-index-by-its-index-number-in-flutter-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!