I'm using accompanist pager for a horizontal pager...
# compose
c
I'm using accompanist pager for a horizontal pager, and I want to programatically move to the next page. I tried this (see what the button does onclick)
Copy code
Column() {
    val pagerState = rememberPagerState(pageCount = 10)

    HorizontalPager(state = pagerState) { page ->
        Text(text = "Page: $page", modifier = Modifier.fillMaxWidth())
    }

    Button(onClick = { pagerState.animateScrollToPage(pagerState.currentPage + 1) }) {
        Text(text = "Test")
    }
}
But I get an error of
Suspend function 'animateScrollToPage' should be called only from a coroutine or another suspend function
I thought it was okay to have an event like this in an onClick event since it's not happening on every recomposition?
k
animateScrollToPage
is a suspend function, need to run this from a coroutine.
Copy code
val scope = rememberCoroutineScope()

scope.launch {
    pagerState.animateScrollToPage(...)\
}
c
Oh. So
Copy code
val scope = rememberCoroutineScope()
is just the typical/standard way to create a coroutine scope in a composable?
k
I think so, is there any other way?
🤔 1
a
Yea that would be the right way to go about it. I think it's needed because animations in compose kinda use suspending functions
k
t
scope.launch {}
shouldn’t be used directly inside compose, should it?
k
It's called on the Button's onClick lambda
t
Oh! I missed that part 😄
d
I do it like this:
Copy code
LaunchedEffect(state.currentPageIndex) {
  pagerState.animateScrollToPage(state.currentPageIndex)
}