https://kotlinlang.org logo
Title
j

jasu

02/13/2022, 2:36 PM
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?
NoteList(
    notes = viewmodel.notes.collectAsState().value,
    onItemClick = { noteId ->
        Log.e(TAG, "NotesListingScreen: noteId: $noteId clicked")
        onEditNote(noteId)
    }
)
@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

Albert Chang

02/13/2022, 4:57 PM
You can use something like
LaunchedEffect(viewmodel.notes) {
    viewmodel.notes.drop(1).collect {
        listState.animateScrollToItem(0)
    }
}
j

jasu

02/14/2022, 5:17 AM
what is the approach @Albert Chang here?
a

Albert Chang

02/14/2022, 7:36 AM
It's basically the same as your code except that it doesn't sroll the list on the initial state.
j

jasu

02/14/2022, 1:09 PM
it doesn’t work dude.
any other idea?
a

Albert Chang

02/14/2022, 2:02 PM
How does it not work?
j

jasu

02/14/2022, 4:30 PM
collect { }
okay collect was not being imported currently, it does work now. Thanks man