I have a LazyRow
containing multiple Card
items that the user can scroll through. I wanted this to be snapping to each of these items, so I added flingBehavior
to the LazyRow
.
My question now is:
How can I add a button that scrolls to the start of the list, i.e. index=0
?
I saw in the documentation that rememberLazyListState
has a function animateScrollToItem(index: @IntRange(from = 0) Int, scrollOffset: Int)
. How would I call this as it requeres a suspend
keyword?
This is the code:
fun DisplayCard(response: List<AlbumDataClassItem>) {
val listState: LazyListState = rememberLazyListState()
LazyRow(
modifier = Modifier.fillMaxSize(),
state = listState,
flingBehavior = rememberSnapFlingBehavior(listState)
) {
items(response) { item ->
Card(
[...]
)
}
}
}
So I found the solution.
val coroutineScope = rememberCoroutineScope()
And then on the function of the button
onButtonClicked = { newActiveButton ->
coroutineScope.launch {
listState.animateScrollToItem(0)
}
Unfortunatly this animation is way to fast.