Search code examples
androidandroid-jetpack-composecomposablejetpack-compose-modalbottomsheet

Prevent back press ModalBottomSheet in Jetpack Compose


I'm using material3:1.2.0-beta01, and I want my ModalBottomSheet to not be swipeable by the user or dismissable if the user does a back press.

I tried adding an empty BackHandler in the ModalBottomSheet Composable, but it doesn't work.

Can you please help?

That's my code:

var showBottomSheet by rememberSaveable { mutableStateOf(false) }
if (showBottomSheet) {
    BackHandler {}
    ModalBottomSheet(onDismissRequest = { }, sheetState = bottomSheetState,
        shape = RoundedCornerShape(size = 12.dp),
        dragHandle = null,
        containerColor = MaterialTheme.colorScheme.errorContainer) {
        BackHandler {}
        Box(modifier = Modifier
            .padding(16.dp) {
            Column {
                // content
                // when clicking on a bouton, we launch a coroutine to hide the sheet
                // and in invokeOnCompletion, we pass showBottomSheet to false 
                content()
            }
        }
    }
}

Solution

  • You have to pass argument for the properties parameter to the ModalBottomSheet.

    It goes like:

    if (openBottomSheet) {
            ModalBottomSheet(
                onDismissRequest = { openBottomSheet = false },
                sheetState = bottomSheetState,
                properties = ModalBottomSheetProperties(
                    isFocusable = true,
                    securePolicy = SecureFlagPolicy.SecureOn,
                    shouldDismissOnBackPress = false
                )               
            ) { ... }
    

    And, for not being swipeable, I guess you want to show whole content. For this, use

    val bottomSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) // this is the state passed to the ModalBottomSheet