Why the View Keeps Flashing When Using Jetpack Navigation with Compose

Lazy Column is blinking when navigating with compose navigation

Your code gives me the following error for cachedIn:

Flow operator functions should not be invoked within composition

You shouldn't ignore such warnings.

During transition Compose Navigation recomposes both disappearing and appearing views many times. This is the expected behavior.

And your code creates a new Pager with a new flow on each recomposition, which is causing the problem.

The easiest way to solve it is using remember: it'll cache the pager flow between recompositions:

val lazyItems = remember {
Pager(PagingConfig(/* ... */)) { /* ... */ }
.flow
.cachedIn(viewModelScope)
.collectAsLazyPagingItems()
}

But it'll still be reset during configuration change, e.g. device rotation. The best way to prevent this is moving this logic into a view model:

class MainScreenViewModel : ViewModel() {
val pagingFlow = Pager(PagingConfig(/* ... */)) { /* ... */ }
.flow
.cachedIn(viewModelScope)
}

@Composable
fun MainScreen(
viewModel = viewModel<MainScreenViewModel>()
) {
val lazyItems = viewModel.pagingFlow.collectAsLazyPagingItems()
}

TopAppBar flashing when navigating with Compose Navigation

The flashing is caused by the default cross-fade animation in more recent versions of the navigation-compose library. The only way to get rid of it right now (without downgrading the dependency) is by using the Accompanist animation library:

implementation "com.google.accompanist:accompanist-navigation-animation:0.20.0"

And then replace the normal NavHost with Accompanist's AnimatedNavHost, replace rememberNavController() with rememberAnimatedNavController() and disable the transitions animations:

AnimatedNavHost(
navController = navController,
startDestination = bottomNavDestinations[0].fullRoute,
enterTransition = { _, _ -> EnterTransition.None },
exitTransition = { _, _ -> ExitTransition.None },
popEnterTransition = { _, _ -> EnterTransition.None },
popExitTransition = { _, _ -> ExitTransition.None },
modifier = modifier,
) {
[...}
}

Jetpack Compose + Navigation - Infinite loop on navigate()

It's because you're trying to navigate from a composable. See the documentation

You should only call navigate() as part of a callback and not as part of your composable itself, to avoid calling navigate() on every recomposition.

You could use a LaunchEffect for instance



Related Topics



Leave a reply



Submit