2

1. The Problem

Is there a way for a ListView.builder to start, say, at the second (index = 1) item of a list of widgets?

In my case — more info here and here if you're interested —, I'm trying to add some empty space at the top of a ListView so the user can scroll the top card closer to his thumb. A workaround would be to add empty Containers to the top and bottom of the List of widgets to simulate empty space. However, the ListView will render the Containers on the screen and user might become confused and not know that there are more cards available by simply scrolling.

Maybe there is a way of doing this with a ScrollController?

2. Some Template Code

I don't think that exposing code will help much because I'm just using a typical ListView.builder, but here it is in case you need a refresher.

ListView.builder(
  itemCount: widgetsList.length,
  itemBuilder: (context, index){
    return widgetsList[index];
  },
),
Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76

2 Answers2

4

You can use a ScrollController and have its initialScrollOffset where you want it to originally be.

  1. Declare your ScrollController inside your widget's class.
    ScrollController scrollController = ScrollController(
      initialScrollOffset: 10, // or whatever offset you wish
      keepScrollOffset: true,
    );
    
  2. Add the controller to your ListView
    ListView.builder(
      controller: scrollController,
      itemCount: widgetsList.length,
      itemBuilder: (context, index){
        return widgetsList[index];
      },
    ),
    

Additionally, you may even want to create animations for the background scrolling action. That is possible through using the .animateTo method inside your widget's initState.

Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
0

initialScrollOffset can be confusing as the initialScrollOffset's value is not the same as index.

This is the solution I have used overtime and it works perfectly well. Use this Package as your ListView Builder scrollable_positioned_list

The package has a property called initialScrollIndex. The value you supply will be the index where the listView will start from, irrespective of how large the data is, it works well.

Most importantly, the value of your initialScrollIndex must not be out of range, so as a good developer, it's essential you check the length of the data before assigning a value to the initialScrollIndex.

StartIndex is the index you want your listView to start from

initialScrollIndex: alldataLength > startIndex ? startIndex : 0

This will safely set the initial index to 0 if the supplied startIndex is out of range.

This works perfectly well, You can try it out !

Amfstacks
  • 121
  • 2
  • 1