Search code examples
kotlinandroid-jetpack-composecompose-desktop

How can I prepend items to a LazyColumn without affecting the current view in Compose Desktop?


I'm working on an app using Compose Desktop, and I have a use case where I need to add new items to the top of a LazyColumn without causing the currently visible items to shift or move. This is important for a smooth user experience.

I maintain a list of items in my ViewModel, and I want to be able to prepend new items to the list, but I don't want these additions to disrupt the user's current view.

Here's a simplified version of my current code:

@Composable
fun MyScreen(viewModel: MyViewModel) {
    val items by viewModel.items.collectAsState()
    LazyColumn {
        items(items) { item ->
            Text(text = item)
        }
    }
}

When I update the items list in my ViewModel, it reflects changes in the LazyColumn. However, newly added items are placed at the bottom of the list, causing the user's view to scroll down, which is not the desired behavior.

Is there a way to efficiently add items at the beginning of the LazyColumn without having the list reposition or causing a scroll jump for the user? Any advice or code examples would be greatly appreciated.

Thank you in advance for your help!


Solution

  • You should use an explicit key, so Compose can track which item is which:

        val items by viewModel.items.collectAsState()
        LazyColumn {
            items(items, { item -> item.someId }) { item ->
                Text(text = item)
            }
        }