flutter ListView scroll to index not available

后端 未结 5 1219
北海茫月
北海茫月 2020-11-30 08:43

What I needed:

I want to scroll a list by some index, how can i do that.

What I know:

scrollToIndex sh

5条回答
  •  广开言路
    2020-11-30 09:13

    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 these suggested solutions/plugins or from other posts like 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 (as mentioned by Slashbin):

    • ScrollablePositionedList
      • dependency: scrollable_positioned_list

    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.)

提交回复
热议问题