3

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

2 Answers 2

2

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) => ...);
1

This information is not available.

The most you can get is the indexes of what has been laid out by RenderSliverList (a lower layer of ListView).

Which is the equivalent of what's visible + a potential extra around it.

4
  • Do you know what are, exactly, firstIndex and lastIndex in the didFinishLayout method? Jul 8, 2018 at 22:06
  • These are the indexes of what has been rendered on screen. It is close to what's visible but may contain a few extra before/after what's actually visible. Jul 8, 2018 at 22:10
  • Why does it need to render widgets which are not visible? Even internally, it doesn't know when to start/end? And if it doesnt know at all, how can it choose a firstIndex and lastIndex to start with, even if they have some extra before/after? Jul 8, 2018 at 22:20
  • I don't know the details, sorry. You can take a peek at RenderSliverList code, which contains all that logic. Jul 8, 2018 at 22:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.