How do I scroll Lazy list to 0th index when there’...
# compose
j
How do I scroll Lazy list to 0th index when there’s new item added, updated or deleted to the list? I’ve currently LaunchedEffect with notes as key but when I come to note list screen from note detail (without creating, updating or deleting the item) it scrolls the list to 0th position regardless of data changed or not?
Copy code
NoteList(
    notes = viewmodel.notes.collectAsState().value,
    onItemClick = { noteId ->
        Log.e(TAG, "NotesListingScreen: noteId: $noteId clicked")
        onEditNote(noteId)
    }
)
Copy code
@Composable
fun NoteList(notes: List<Note>, onItemClick: (String) -> Unit) {
    val listState = rememberLazyListState()

    LaunchedEffect(key1 = notes) {  // when any item changes, scroll list to 0th index
        listState.animateScrollToItem(0)
    }
}
a
You can use something like
Copy code
LaunchedEffect(viewmodel.notes) {
    viewmodel.notes.drop(1).collect {
        listState.animateScrollToItem(0)
    }
}
j
what is the approach @Albert Chang here?
a
It's basically the same as your code except that it doesn't sroll the list on the initial state.
j
it doesn’t work dude.
any other idea?
a
How does it not work?
j
Copy code
collect { }
okay collect was not being imported currently, it does work now. Thanks man