Home > other >  How to handle back button click in a Dialog in Jetpack Compose?
How to handle back button click in a Dialog in Jetpack Compose?

Time:12-19

I am showing a custom dialog when there is no internet connectivity. I want to do some handling when the user presses the back button while the dialog is visible.

BackHandler inside the parent screen nor within the dialog itself is working in this scenario.

Thank you

CodePudding user response:

Use the onDismiss callback and disable automatic dismissal when the user taps outside the dialog. This way you can ensure that the dismiss request originated from a back press. This is a workaround, of sorts, since an out-of-the-box API is not yet bundled with Compose.

CodePudding user response:

Just define the BackHandler function inside the Dialog:

val shouldShowDialog = remember { mutableStateOf(true) }

if (shouldShowDialog.value) {

    Dialog(onDismissRequest = { shouldShowDialog.value = false }) {
        Button(onClick = {shouldShowDialog.value = false}){
            Text("Close")
        }

        BackHandler {
            // your action
        }
    }
}
  • Related