Adib Faramarzi
08/10/2021, 9:55 AMback pressed
state for compose-navigation?
popBackStack
does not finish navigation (and instead just removes the destination) but pressing the back key always works perfectly.
This becomes a problem when you have nested navigation as the inner navigation stacks can never pop themselvesnitrog42
08/10/2021, 10:00 AMAdib Faramarzi
08/10/2021, 10:01 AM2.4.0-alpha06
nitrog42
08/10/2021, 10:01 AMAdib Faramarzi
08/10/2021, 10:02 AMnitrog42
08/10/2021, 10:05 AMIan Lake
08/10/2021, 1:52 PMNavController.popBackStack() returns a boolean indicating whether it successfully popped back to another destination. The most common case when this returns false is when you manually pop the start destination of your graph.
When the method returns false, NavController.getCurrentDestination() returns null. You are responsible for either navigating to a new destination or handling the pop by calling finish() on your Activity
false
as your signal to call popBackStack()
on your outer NavControllerAdib Faramarzi
08/10/2021, 1:53 PMIan Lake
08/10/2021, 1:56 PMpopBackStack()
should also be taking a lambda to trigger when that returns false
- that would be how you'd encapsulate the access to the outer NavControllerAdib Faramarzi
08/10/2021, 2:00 PMpopBackStack()
)
I have a back button in the inner-navigation page which should pop its page. Currently it is using popBackStack
.
I think what might be better is passing a onBackPressed
into the function that is rendering this page (which is a NavHost
and handle the back there (pop the backstack of the parent nav controller).Ian Lake
08/10/2021, 2:04 PMAdib Faramarzi
08/10/2021, 2:05 PMIan Lake
08/10/2021, 2:06 PMAdib Faramarzi
08/10/2021, 2:07 PMnitrog42
08/10/2021, 2:40 PMNavHost(navController = navController, startDestination = nav_home) {
composable("home") {
Text("Home")
}
navigation(startDestination = "profile/", route = "profile") {
composable("profile/") {
Button(onClick = { navController.popBackStack() }) {
Text("Should go to home") // But display blank page instead
}
}
}
}
Colton Idle
08/10/2021, 3:17 PMval dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher
BackHandler(enabled = pagerState.currentPage > 0) {
viewModel.updateCurrentPage(pagerState.currentPage.minus(1))
scope.launch { pagerState.animateScrollToPage(pagerState.currentPage.minus(1)) }
}
And my top bar is declared like this
topBar = {
MyTopAppBar(navBackIconClicked = { dispatcher.onBackPressed() })
@Adib Faramarzi maybe you'll find this useful.Ian Lake
08/10/2021, 3:25 PMBackHandler
. Just double check that behavior is actually what you want or if you want to bypass those to only swap back pages, no matter what internal BackHandlers exist (i.e., make the signal explicit as we've been talking about)