I’m having some issues with state and navigation in Compose.
I have a screen A with a searchbar. When a result of the search is clicked it navigates to a detail screen and when I navigate back, screen A is back to its initial state (no results, no search bar input, etc). Is there a way to maintain state of screen A when navigating back from detail screen?
I have tried with saveState and restoreState with no luck. I don’t know if this is a navigation configuration, or something else…
See video of problem -> https://youtube.com/shorts/j8qRdUu5dNI?feature=share
This is my NavHost:
SharedTransitionLayout {
NavHost(
modifier = Modifier.fillMaxSize().padding(padding).background(MaterialTheme.colorScheme.background),
navController = navController,
startDestination = CardSearchRoute
) {
composable<CardSearchRoute> {
val viewModel = koinViewModel<CardSearchViewModel>()
val state by viewModel.state.collectAsStateWithLifecycle()
CardSearchScreen(
state = state,
onEvent = viewModel::onEvent,
animatedVisibilityScope = this,
onCardClicked = {
navController.navigate(CardDetailRoute(cardID = it.id))
}
)
}
composable<CardDetailRoute> { backStackEntry ->
val cardID = backStackEntry.toRoute<CardDetailRoute>().cardID
val viewmodel = koinViewModel<CardDetailViewModel>(parameters = { parametersOf(cardID) })
val state by viewmodel.state.collectAsStateWithLifecycle()
CardDetailScreen(
state = state, animatedVisibilityScope = this,
onEvent = {}
)
}
composable<ComingSoonRoute> {
todoScreen("Collection")
}
composable<ScanRoute> {
todoScreen("Scanning")
}
}
}