I'm trying to add a "reset the saved bottom nav st...
# compose
m
I'm trying to add a "reset the saved bottom nav stack" on demand. Something like:
Copy code
fun NavController.navToBottomNavItem(route: String, startFromStackRoot: Boolean = false) = navigate(route) {
    //how to use [startFromStackRoot]?
    popUpTo(DashboardScreenDestination.route) {
        saveState = true
    }
    launchSingleTop = true
    restoreState = true
}
The scenario in our app is, there's a botom menu and there's a Dashboard stack (app starts on that) and a Shop stack. The code above makes sure that when user navigates between different bottom bar items, he isn't starting from the root of the stack, but ends up where he left. So far so good. But there's one scenario, where I want to go from Dashboard directly to the root of the Shop stack, without restoring it's state. E.g. using the
startFromStackRoot
param.
After trying a few different ideas and digging into the source code of NavController, I'm beginning to think it's not possible the way NavController / NavOptions apis are designed. Seems like these backstacks are stored inside
backStackStates
and we can't just e.g. find and clear a backstack by some id. Just invoking
restoreState
conditionally will work (it will start from root) but the old Shop stack state will still remain saved and it will be restored on another occasion while what we want is for the fresh one to be saved
Another idea was to switch to the other stack, make it restore its state and then immediately popBackStack all the way up to the Shop stack root. But that didn't work either, probably due to some race condition.
i
FWIW, NavController synchronously updates its state when you call navigate(), popBackStack (), etc. There's no way to "race", since the state is already up to date
m
Thanks for that insight. Must have been something else. Anyway, I'm out of ideas
i
Also:
we can't just e.g. find and clear a backstack by some id
But that's exactly what
clearBackStack()
does: https://developer.android.com/reference/kotlin/androidx/navigation/NavController#clearBackStack(kotlin.String)
So,
clearBackStack()
followed by
navigate()
seems like it would do exactly what you want?
m
Oh, this is something that we tried too, but I think we need to revisit because the Shop destination is parameterised and we might have just used wrong id.
i
You have to use the exact route as your
route
when you declared your destination. That exact string, `{id}`s and all
m
Yeah,. because it uses hashCode on the whole route, makes sense 🙂
I'll play around that