How to prevent autoscroll on LazyColumn update if ...
# compose
k
How to prevent autoscroll on LazyColumn update if item index 0 is not visible?
Every new item that arrives as index 0 makes scroll move for that item height.
f
Can you share the code?
k
I am unable to share code as it's company project. Should adding an new item to an index 0 not move scroll for that same height amount?
🤣 1
d
and we are unable to answer questions like "I can't show you what I do but what am I doing wrong?"
k
I am asking a question, in a sense of, is something true or false. Sorry for not being able to share code.
Should adding an new item to an index 0 not move scroll for that same height amount?
d
nobody ask you to violate NDA, you can easily share some part of it, replacing sensitive data with "something" - just like in previous question
generally it works like "i want some behavior from this code, and it works in another way plz help"
k
Lol, okay mate. Here it is.
Copy code
val lazyListState = rememberLazyListState()
    LazyColumn(
        state = lazyListState,
        reverseLayout = true,
        modifier = modifier
    ) {
        items(messages) { item ->
            MessageItem(item)
        }
}
âž• 1
a
If you don't provide key then index is used as key. Now assume this nth item is focused and another item at index 0 is added. So now new nth item (previously (n-1)th item) is now focused. Try providing unique key per item(message) to items extention function
✅ 1
âž• 2
k
Thanks. This solved issue. I was using sealed class for my data and sealed class did not contain any properties. Passing an id to a sealed class and as a key inside
items(..,key={id})
solved an issue.
My first issue was solved with keys, but I've found different issue now. Scrolling to the end of list and Navigating from Screen A that contains this LazyColumn, to Screen B, and returning does not position scroll correctly. Using something like this solves the problem, but looks like hack. Am I missing something? Worth mentioning is that I am showing messages and pictures from the device storage with Coil.
Copy code
val itemOffset = rememberSaveable { mutableStateOf(0)}
    LaunchedEffect(itemOffset) {
        lazyListState.animateScrollToItem(lazyListState.firstVisibleItemIndex, itemOffset.value)
    }

    SideEffect {
        itemOffset.value = lazyListState.firstVisibleItemScrollOffset
    }
j
For your second issue you need to hoist the LazyListState up so that it is remembered by whatever is composing Screen A, Otherwise a new LazyListState is going to be created and this contains the scroll position.
🙌 1
296 Views