When I add some items on top of the ListView
it scrolls to the top item on the 0
index. But I need it to stay in the same position as before adding items.
For example, chat history pagination on the top of the list of messages, if I open any messenger (Telegram, WhatsApp, etc.) open chat with a long history and scroll down downloading the history. History will be added to the top of the list (from the server ~20 messages at a time) but the list will stay on the same position (while scrolling).
Flutter ListView
behaves like that if you add to the bottom, but if you add to the top it jumps to the first added item. I want it to stay.
2
Answers
Screenshot:
Since you didn’t share any code, I just created a simple demo to show how you can achieve the effect like a messaging app. The code is very simple to understand, I have used comments almost everywhere.
Code (Null safe):
The solution proposed by @CopsOnRoad works if your feed can expand in one direction only.
This solution works for appending items to the top and the bottom of the list. The idea of the solution is the following. You create two SliverLists and put them inside CustomScrollView.
The first list scrolls upwards while the second list scrolls downwards. Their offset zero points are fixed at the same point and never move. If you need to prepend an item you push it to the top list, otherwise, you push it to the bottom list. That way their offsets don’t change and your scroll view does not jump.
You can find the solution prototype in the following dartpad example.