Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pop up to start destination (Compose Navigation)

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?

like image 620
SmallGrammer Avatar asked Dec 31 '25 20:12

SmallGrammer


1 Answers

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
}
like image 124
Byte Code Avatar answered Jan 03 '26 11:01

Byte Code



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!