Has anyone had issues with using a drawer and jetp...
# android
n
Has anyone had issues with using a drawer and jetpack navigation? I’m using material 2 (
androidx.compose.material:material:1.5.4
which is from the latest Compose BOM and the latest Jetpack Navigation version (2.7.6)) like this:
Copy code
val scope = rememberCoroutineScope()
val scaffoldState = rememberScaffoldState()
BackHandler(enabled = scaffoldState.drawerState.isOpen) {
    coroutineScope.launch { scaffoldState.drawerState.close() }
}
Scaffold(
    scaffoldState = scaffoldState,
    topBar = { AppTopBar() }
    drawerContent = { AppDrawer() },
    content = { HomeScreen() }
)

HomeScreen() {
    NavHost(...) { ... }
}
The issue is that my
BackHandler
only works if I’m on the root of my navigation graph. If I am not, the screens are popped off the backstack until we are at the root. The reason is
NavHost
has the following in the implementation:
Copy code
BackHandler(currentBackStack.size > 1) {
    navController.popBackStack()
}
which means that its
BackHandler
is added to the composition last and so it is the one that is enabled.
navController.enableOnBackPressed(false)
doesn’t seem to impact behavior at all. has anyone else ran into this? any suggestions?
If anyone else runs into this — the solution is to do
Copy code
val scope = rememberCoroutineScope()
val scaffoldState = rememberScaffoldState()
if(scaffoldState.drawerState.isOpen) {
    BackHandler(true) {
        coroutineScope.launch { scaffoldState.drawerState.close() }
    }
}
Scaffold(
    scaffoldState = scaffoldState,
    topBar = { AppTopBar() }
    drawerContent = { AppDrawer() },
    content = { HomeScreen() }
)

HomeScreen() {
    NavHost(...) { ... }
}