Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
replace GlobalScope.launch in jetpack compose

I am writing some pager code in jetpack compose and came to a situation where I need to change page number by button click. This is my event on button click:

onClick = {pagerState.scrollToPage(page=currentPager+1)}

but when I do this I get this error: Suspend function 'scrollToPage' should be called only from a coroutine or another suspend function

I got a solution to this by adding:

onClick = {GlobalScope.launch (Dispatchers.Main) {pagerState.scrollToPage(page=currentPager+1)}}

but still GlobalScope.launch is not recommended. Above onClick are called inside basic compose functions. How can I fix this issue in jetpack compose?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Go through this documentation : Accompanist Pager

Here is a raw code: Raw code for scroll to page

If you want to jump to a specific page, you either call call pagerState.scrollToPage(index) or pagerState.animateScrollToPage(index) method in a CoroutineScope:

val pagerState = rememberPagerState()
val scope = rememberCoroutineScope()

HorizontalPager(count = 10, state = pagerState) { page ->
    // ...page content
}

// Later, scroll to page 2
scope.launch {
    pagerState.scrollToPage(2)
}
over 4 years ago · Santiago Trujillo Relatório

0

You should use the code below to create a coroutines scope in your composable.

val coroutinesScope = rememberCoroutineScope()

Note that you can only call this inside a composable so you cannot create coroutinesScope inside your onClick() and have to initialize it on the top of your composable.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda