Hello, I need to scroll to bottom of the LazyColum...
# compose
a
Hello, I need to scroll to bottom of the LazyColumn when a new item is added. Please check the code in thread, I feel my code is bit hacky and I’m keen to know if there is a better approach.
2
Copy code
@Composable
fun HomeScreenTaskList(newList: List<Task>) {
    val listState = rememberLazyListState()
    val currentListSize = remember { mutableStateOf(newList.size) }

    val scrollToBottom = newList.size > currentListSize.value
    currentListSize.value = newList.size

    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        state = listState,
        contentPadding = PaddingValues(5.dp)
    ) {
        items(items = newList,
            itemContent = {
                TaskListItemView(task = it)
            })
    }

    LaunchedEffect(newList) {
        if (scrollToBottom) {
            listState.animateScrollToItem(newList.size)
        }
    }
}
z
I think you can do the size comparison and update the “current size” in the effect. In fact, you wouldn’t even need the current size, you could just use a flow:
Copy code
val updatedList by rememberUpdatedState(newList)

…

LaunchedEffect(updatedList) {
  snapshotFlow { updatedList }
    .map { it.size }
    .distinctUntilChanged()
    .collectLatest { size ->
      listState.animateScrollToItem(size)
    }
}
a
thanks a lot @Zach Klippenstein (he/him) [MOD]. I ended up with below code, to avoid scrolling on first composition and when item is removed
Copy code
val updatedList by rememberUpdatedState(list)

...

    LaunchedEffect(Unit) {
        snapshotFlow { updatedList }
            .map { it.size }
            .distinctUntilChanged { oldSize, newSize -> newSize < oldSize }
            .drop(1)
            .collectLatest {
                listState.animateScrollToItem(it)
            }
    }
r
@Aditya Thakar your code won’t work when your list size is shrinked to mimimun and then added some items