DEV Community

Cover image for How to make a `ListView.builder` Start from a specific index in flutter.
AJALA MAYOWA FELIX
AJALA MAYOWA FELIX

Posted on

1

How to make a `ListView.builder` Start from a specific index in flutter.

I was working on a chat application which I used ListView.builder to render the chat messages.

I had a problem of resuming from the last message read by the user, this poses a bad user experience if users can not resume from the last read message as most chat applications do.

Programmatically, I need to start the chat message lists from the index of the last read message by the user.

  • Get the index of the last read message
  • Assign the index to the list view builder

I checked online for solutions and tips, I found out so many developers faced the same problem but I could not found any tangible solution.

After so many personal approaches I finally settled for the one with the best user experience and well optimised.

There is a dart package on pub spec

scrollable_positioned_list

Use the package as your listView builder.

The package has a property called **initialScrollIndex**.

The value you assign to the initialScrollIndex 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 your listview is building before assigning a value to the initialScrollIndex.

Using StartIndex as the index you want your listView to start from, and alldataLength is the total length of all the chat messages you are loading.

initialScrollIndex: alldataLength > startIndex ? startIndex : 0
Enter fullscreen mode Exit fullscreen mode

The above code safely prevents your app from crashing by ensuring that your startindex is not out of range of the alldataLength.

ScrollablePositionedList.builder(
  itemCount: alldataLength,
  itemBuilder: (context, index) => Text('Item $index'),
  initialScrollIndex: alldataLength > startIndex ? startIndex : 0 
);
Enter fullscreen mode Exit fullscreen mode

keep fluttering!
Cheers!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️