How to add the listeners on the Vertical Pager in compose?

211 Views Asked by At

I want to know how can I add a similar registerOnPageChangeCallback in VerticalPager as we already have ViewPager2. I want to perform some tasks when the pager is in an idle state. but the problem is that the VerticalPager block calls multiple times for the same position and can't find anything else similar to perform this task.

 VerticalPager(state = pagerState){    
 }

this block calls multiple times in the same position and I have some tasks that I have to perform a single time in this block

1

There are 1 best solutions below

1
On

You can do it by checking current page by passing indices to your pages and

val offset = pagerState.currentPageOffset

And using both in a derivedState you can trigger a function inside LaunchedEffect.

It would also be better a boolean for if this is current page and currentPageOffsetFraction if there is nothing else to be done with pagerState.

@Composable
fun MyPage(index: Int, pagerState: PagerState) {

    val currentPageOffsetFraction = pagerState.currentPageOffsetFraction


    val doSomething by remember {
        derivedStateOf {
            pagerState.currentPageOffsetFraction == 0f && index == pagerState.currentPage
        }
    }


    val context = LocalContext.current


    LaunchedEffect(key1 = doSomething) {
        if (doSomething) {
            Toast.makeText(context, "Page opened", Toast.LENGTH_SHORT).show()
        }
    }

    Column(modifier = Modifier.fillMaxSize()) {

        Text(text = "Offset: $currentPageOffsetFraction")
    }
}