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
Use the package as your listView builder.
The package has a property called
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
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
The above code safely prevents your app from crashing by ensuring that your
startindex is not out of range of the
ScrollablePositionedList.builder( itemCount: alldataLength, itemBuilder: (context, index) => Text('Item $index'), initialScrollIndex: alldataLength > startIndex ? startIndex : 0 );