Hello, is there a way to clear the whole back stack when using navigation with compose? sometimes t...
r
Hello, is there a way to clear the whole back stack when using navigation with compose? sometimes the start/initial route might be already popped, in that case:
Copy code
popUpTo(Route.initial) { inclusive = true }
doesn't seem to work and all the routes after initial are still present. Is there a way to make sure we clear the back stack without knowing about the first route in the graph?
j
This is what I ended up doing:
Copy code
navController.navigate("home") {
  popUpTo(navController.backStack.first.destination.id) { inclusive = true }
}
Not sure if it’s the best way: @Ian Lake , if available, might want to chime in 🙂 on this one.
r
This works well, thank you! Although
backStack
on
NavController
is restricted to library, maybe there is indeed another way.
i
Well, you should never be popping the entire back stack as per the Principles of Navigation (if you are doing that, it usually means you've set up your graph with conditional destinations as your start destination, which you shouldn't do): https://developer.android.com/guide/navigation/navigation-principles#fixed_start_destination
👍 1
Of course, what you really want is the ID of the graph itself:
navController.graph.id
👍 1
j
Cool!
navController.graph.id
looks much better. Is
navController.graph.id
always equal to the id of the
NavHost
’s
startDestination
? I’ve RTFM:
Copy code
/**
 * NavGraph is a collection of {@link NavDestination} nodes fetchable by ID.
 *
 * <p>A NavGraph serves as a 'virtual' destination: while the NavGraph itself will not appear
 * on the back stack, navigating to the NavGraph will cause the
 * {@link #getStartDestination starting destination} to be added to the back stack.</p>
 */
Seems it’s a “yes” :)
r
@Ian Lake Thanks for the post and the solution. Really helpful! In my usecase, I need to remove the signup flow (1 route) once signup is completed and similarly, remove the splash screen (the start destination at all times) after initial loading.. What would be the recommended way for these cases?
2
i
Those are exactly the use cases that should never, ever be your start destination, so much so that we have docs specifically around how you should be handling login (https://developer.android.com/guide/navigation/navigation-conditional#login) and have talked about a lot of those edge cases in the Navigating Navigation talk:

https://www.youtube.com/watch?v=09qjn706ITA&amp;t=273s

Think about the process recreation case: your state is saved and restored and with that, your current destination is restored. That means that a splash destination isn't run, a login destination isn't checked to make sure login credentials are still valid, etc.
1542 Views