I got a LazyColumn where I want to implement a "sc...
# compose
s
I got a LazyColumn where I want to implement a "scroll to top" functionality. Doing
lazyListState.scrollToItem(0)
seems to work when I got the full list of items in my LazyColumn in-memory. However when I switch over to backing my LazyColumn items with a list coming from a
androidx.paging.compose.LazyPagingItems<Foo>
then doing
lazyListState.scrollToItem(0)
just scrolls like ~90 items only and I can't tell why that is. When I query
lazyListState.layoutInfo.totalItemsCount
it does have the real total amount, so it looks like my LazyColumn is aware of all the items it has. It however still does not manage to scroll all the way. Has someone had to do this before and has some idea how to properly support that?
1
Note that if I do something like this:
Copy code
LazyColumn() {
  item(key = "just so that this is always in-memory") {
    Box(Modifier.size(1.dp))
  }
  items(
    count = lazyPagingItems.itemCount,
    key = lazyPagingItems.itemKey(...),
    contentType = lazyPagingItems(...),
  ) { index ->
    val item = lazyPagingItems[index]
  }
}
Then if I
scrollToItem(0)
it does this weird thing where it will just scroll continuously ~90 items at a time till it reaches that first item. But it does so gradually, probably making the Pager gradually bring more and more data till it reaches the end. I would optimally like it to just jump to the right index immediately. I do have
jumpThreshold
set in my Pager, but it doesn't seem to be doing it properly 🤷
Wow, if I do
lazyListState.scrollBy(Float.MAX_VALUE)
instead of
lazyListState.scrollToItem(0)
it seems to work and jump properly to the end without doing it gradually. Without even having to do the
item{ Box(size1.dp) }
hack.
Welp, it was 100% my bad after all. Inside my
items{}
block I was doing this:
Copy code
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
Copy code
items(...) { index ->
  val item = lazyPagingItems[index]
  if (item != null) {
    UiForItem(item)
  } else {
    SomePlaceholderWithAtLeast1dpSize()
  }
}
Just fixed everything, it scrolls to 0, shows only placeholders for a brief moment but loads the items from DB immediately afterwards. I am so glad I fixed it now, but I lost so much time on this, it's actually incredibly it never crossed my mind before 🤦‍♂️