Youb
Youb

Reputation: 215

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()
            }
        }
    }
}

Upvotes: 3

Views: 1560

Answers (2)

Ashik Azeez
Ashik Azeez

Reputation: 444

If you are using androidx.compose.material3.ModalBottomSheet then use ModalBottomSheetDefaults.properties(shouldDismissOnBackPress = false)

Sample:

 ModalBottomSheet(
        onDismissRequest = {},
        sheetState = modalBottomSheetState,
        dragHandle = { BottomSheetDefaults.DragHandle() },
        content = {
           
        }, containerColor = color,
        properties = ModalBottomSheetDefaults.properties(shouldDismissOnBackPress = false)
    )

Upvotes: 2

Curious Head
Curious Head

Reputation: 100

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

Upvotes: 6

Related Questions