Search code examples
listviewflutter

How to make a `ListView.builder` Start at a Specific Index


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];
  },
),

Solution

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