Archie
11/02/2020, 4:13 PMBottomNavigation
in the bottomBar of the Scaffold
when I am in a certain screen (which for this sample code is ScreenC). But everytime I get to ScreenC, it goes ScreenC and immediately jumps back to startDestination, ScreenA. Am I doing something wrong here?
@Composable
fun Main() {
SampleAppTheme {
val navController = rememberNavController()
val currentBackStackEntry by navController.currentBackStackEntryAsState()
Scaffold(
topBar = {
...
},
bottomBar = {
val currentRoute = currentBackStackEntry?.arguments?.get(KEY_ROUTE)
if (currentRoute != ScreenC.route) {
BottomNavigation {
BottomNavigationItem(
icon = { Icon(Icons.Default.Home) },
selected = true,
onClick = {}
)
BottomNavigationItem(
icon = { Icon(Icons.Default.PieChart) },
selected = false,
onClick = {}
)
BottomNavigationItem(
icon = { Icon(Icons.Default.Person) },
selected = false,
onClick = {}
)
}
}
}
) {
val modifier = Modifier.padding(it)
NavHost(
navController = navController,
startDestination = ScreenA.route,
) {
composable(ScreenA.route) {
MyScreen(modifier, "A", "", "to B") {
navController.navigate(ScreenB.route)
}
}
composable(ScreenB.route) {
MyScreen(modifier, "B", "", "to C") {
navController.navigate(ScreenC.route)
}
}
composable(ScreenC.route) {
MyScreen(modifier, "C", "","to A") {
navController.navigate(ScreenA.route)
}
}
}
}
}
}
Ian Lake
11/02/2020, 4:29 PMlen
11/02/2020, 11:33 PMMaterialTheme.colors
from a preference (light/dark mode) restarts the backstack to the startDestination. I believe this happens because on recomposition, the NavGraphBuilder.()
function is remembered (NavHost.kt #61) and this function won't give the same reference when it recomposes, so the block inside the remember will run and create a new graph.
I've workarounded this issue by adding
var navhost: (@Composable () -> Unit)? = null
And initializing my navhost in my Scaffold's body content with
if (navhost == null) {
navhost = {
NavHost(...) {
}
}
}
navhost?.invoke()
But this is of course not an ideal solution, I only did this to make sure where the issue is happeningIan Lake
11/02/2020, 11:37 PMlen
11/02/2020, 11:38 PMIan Lake
11/02/2020, 11:41 PMlen
11/03/2020, 12:00 AMIan Lake
11/03/2020, 12:01 AMArchie
11/03/2020, 3:06 AMIan Lake
11/03/2020, 3:58 AMArchie
11/03/2020, 3:59 AM