I am having some issues with LazyListState and the...
# compose
b
I am having some issues with LazyListState and the initial scroll position. In some cases I am trying to set the position to the last item in the list. This works for smaller lists, say 20 items. But when I get to larger lists I seem to end up in the middle of the list. Code in reply
Copy code
@Composable
private fun Items(
   items: LazyPagingItems<ListItem>
) {
   val scope = rememberCoroutineScope()
   val listState = rememberLazyListState(items.itemCount - 1)
About a simple as you get. Not seeing anything in the logs indicating that it attempted and failed. Any idea where I can start looking?
n
The index you pass to
rememberLazyListState()
is the initial index, this would only work for the very first set of items
b
Agreed, I get that. So with my example above is it correct to assume that I should start at the bottom of my list?
n
Yeah but your items change. I’m not confident with paging library but just so you understand, it may be that at first it loads 20 items and correctly goes to position #19, than it loads another page (20+20=40), the node is recomposed but your index has no effect - it’s not reapplied
b
Ok, I mean this makes sense, but seems like a pretty big limitation with LazyListState when using a pager. This means that I cannot scroll to a position that is not yet been loaded by the pager? Even this won’t update my position correctly:
Copy code
LaunchedEffect(items.itemCount) {
   scope.launch {
      listState.scrollToItem(items.itemCount - 1)
   }
}
Of course even if that code worked, from a UX standpoint it would be awful
n
Yeah, I’d rather work with the data source (backend, db) to emit items in reverse order so you can leverage real pagination. Otherwise just load everything beforehand in a List and don’t use pagination at all
b
Again, this was just an example to try and figure out what was wrong. I want to place users where they last left off in the list. This could often times be somewhere in the middle of the list, so it would matter if I go in reverse order or not. In either direction if the last item that was read is outside the loaded pages I will run into a problem. A little more work, but I think this can be fixed by calculating the page the users index will land on and start the pager on that page.
I appreciate the help and the quick spot of the issue!
n
Well your code above - besides scope.launch which is not needed - should work. You can also use the state count (state.totalItemsCount , something like that) to make sure the state is aware of the new items
b
I won’t spend too much time on figuring out what I am doing wrong there. Jumping the user around to correct index as items load is going to be a really bad experience. Either moving away from paging or starting on the page containing the index should fix my issue.
👍 1