In a Flutter ListView, how do I know the index number of the first and last items in view?

Issue

Given a ListView, which is scrolled by some offset, how do I know the index number of the first and last items currently in view?

I have tried this:

class MySliverChildBuilderDelegate extends SliverChildBuilderDelegate {
  MySliverChildBuilderDelegate(IndexedWidgetBuilder builder, {int childCount})
      : super(builder, childCount: childCount);

  @override
  void didFinishLayout(int firstIndex, int lastIndex) {
    print("firstIndex = $firstIndex / lastIndex = $lastIndex");
  }
}

And then:

SliverChildBuilderDelegate childrenDelegate =
    MySliverChildBuilderDelegate(itemBuilder, childCount: childCount);

ListView.custom(
    controller: _controller,
    childrenDelegate: childrenDelegate));

But those firstIndex and lastIndex are not actually what I though they were…

Solution

As of 2020, I guess the answer to this question would be to use a ScrollablePositionedList (https://pub.dev/packages/scrollable_positioned_list) instead of a ListView.

Then you can monitor which items are visible on screen:

itemPositionsListener.positions.addListener((positions) => ...);

Answered By – MarcG

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *