I am in a paged list, and I have scrolled quite far from the beginning of the list, say 30+ pages. At this point I would like to have a way to scroll all the way to the beginning, without having to invalidate my PagingSource.
When I try to do this by calling lazyListState.animateScrollToItem(0)
it just goes to the 0th item of the currently presented items from the pager which is just the 0th item of the currently presented items from the Pager.
The one thing which I did and it seems to work but is super janky is something silly like this
val knownFirstItem = database.getFirstItemWithoutPaging()
val getItemInfo = { lazyListState.layoutInfo.visibleItemsInfo.firstOrNull() }
if (getItemInfo() != null) {
do {
lazyListState.animateScrollToItem(0)
val itemInfo = getItemInfo()
} while (itemInfo != null && itemInfo.key != knownFirstItem?.id)
}
Turns out I was wrongly laying out the items in the LazyColumn itself.
My LazyColumn items looked like this:
items(...) { index ->
val item = lazyPagingItems[index]
if (item != null) {
UiForItem(item)
}
}
But this meant that for the items that were not loaded yet I was not rendering anything. So the lazy layout did not know how to scroll to there, as there was nothing there at all. So it only scrolled to whatever it could. Changing this to
items(...) { index ->
val item = lazyPagingItems[index]
if (item != null) {
UiForItem(item)
} else {
SomePlaceholderWithAtLeast1dpSize()
}
}
Fixed this immediately. It scrolls to 0, shows only placeholders for a brief moment but loads the items from DB immediately afterwards.