I'm using the Navigation Component for Jetpack Compose.
I'm having troubles in clearing my backstack to contain only the starting destination when I navigate.
For example, if I have 3 screens A, B, C and D with A being my start destination.
My navigation might look like:
A -> B -> A -> C
Let's say I wish to clear the back stack to A when I'm navigating from C to D.
This is what happens when I do:
navController.navigateToD {
popUpTo(navController.navGraph.startDestinationId) {
inclusive = false
}
}
A -> B -> A -> D
My backstack will look like that because it matches the startDestinationId to A and therefore will pop up to the first A entry it finds and not to the root.
I've tried to use popUpTo(navController.navGraph.id) and that pops the whole backstack and doesn't leave the start destination in the stack.
Can anyone help me with trying to pop up to the start destination in this scenario?
Also can anyone help to explain the backQueue and what is navGraph.id? Because I'm finding the first element of navController.backQueue to not be my starting destination.
It also seems destination.id is not unique for each backstack entry but is unique for each destination instead?
First of all, why do you have 2 screen A in your back stack.
A is your start destination and you navigated from A -> B.
From B you navigated to A and your back stack became A -> B -> A.
Instead of navigating to A from B. You should call navController.popBackStack() and your back stack will be just A instead of A -> B -> A.
Because you have 2 A in your back stack, when you navigate from C to D. You back stack is cleared up to the second A and become A -> B -> A -> D. I think this is the normal behavior. If your back stack had one A, it would work as you expected.
Secondly, if you want to clear the whole back stack just keep the startDestination when navigation to a screen you can call the below extension function.
fun NavHostController.navigateSingleTopToAndRetainState(route: String) = this.navigate(route) {
popUpTo(
this@navigateSingleTopToAndRetainState.graph.findStartDestination().id
) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With