Mark
02/07/2024, 9:35 AMScaffold with a navigation drawer, I noticed that back handling (i.e. when drawer is open, back button closes the drawer) is not working out of the box. Which approach do you use to handle this? Overriding onBackPressed; onBackPressedDispatcher; compose BackHandler; adding an entry to back stack; something else? Note: I’m still using legacy androidx navigation.Joel Denke
02/07/2024, 9:39 AMval sheetState = _rememberModalBottomSheetState_(skipPartiallyExpanded = true)
val coroutineScope = _rememberCoroutineScope_()
_BackHandler_(enabled = sheetState.isVisible) *{*
coroutineScope
._launch_ *{* sheetState.hide() *}*
.invokeOnCompletion *{*
if (!sheetState.isVisible) {
navigator.finish(onDismiss())
}
}
}
_ModalBottomSheet_(
modifier = Modifier._fillMaxWidth_(),
content = *{*
content(model) *{* result *->*
coroutineScope._launch_ *{*
try {
sheetState.hide()
} finally {
navigator.finish(result)
}
}
}
*}*,
sheetState = sheetState,
onDismissRequest = *{* navigator.finish(onDismiss()) *}*,
)Mark
02/07/2024, 9:49 AMBackHandler needs to be used in the Scaffold content slot, not the drawerContent slotJoel Denke
02/07/2024, 9:55 AMJoel Denke
02/07/2024, 9:55 AMJoel Denke
02/07/2024, 9:57 AMMark
02/07/2024, 10:09 AMMark
02/07/2024, 10:12 AMDialog works, it uses:
onBackPressedDispatcher.addCallback(this) {
if (properties.dismissOnBackPress) {
onDismissRequest()
}
}
although that of course is Android-onlyJoel Denke
02/07/2024, 10:24 AMJoel Denke
02/07/2024, 10:25 AMLocalOnBackPressedDispatcherOwner as well btw 🙂Mark
02/07/2024, 10:38 AMdrawerContent slot like this:
val onBackPressedDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
if (onBackPressedDispatcher != null && scaffoldState.drawerState.isOpen) {
DisposableEffect(Unit) {
val callback = object : OnBackPressedCallback(enabled = true) {
override fun handleOnBackPressed() {
scope.launch {
scaffoldState.drawerState.close()
}
}
}
onBackPressedDispatcher.addCallback(callback)
onDispose {
callback.remove()
}
}
}Mark
02/07/2024, 10:41 AMif (scaffoldState.drawerState.isOpen) {
BackHandler {
scope.launch {
scaffoldState.drawerState.close()
}
}
}Mark
02/07/2024, 10:41 AMenabled instead of wrapping in a conditional statementJoel Denke
02/07/2024, 10:41 AMJoel Denke
02/07/2024, 10:44 AMJoel Denke
02/07/2024, 10:45 AMMark
02/07/2024, 10:50 AMJoel Denke
02/07/2024, 10:54 AMMark
02/07/2024, 10:54 AMJoel Denke
02/07/2024, 11:08 AMMark
02/07/2024, 11:13 AMonBackPressed: (Screen) -> Boolean which allows me to workaround this for now. I’ll revisit when I migrate the compose navigation logic.