kotlinandroid-jetpack-composeonbackpressedjetpack-compose-modalbottomsheet

Handling Back Press during ModalBottomSheetLayout Animation in Jetpack Compose


I encountered an issue when using the ModalBottomSheetLayout component in Jetpack Compose. Here is my code:

ModalBottomSheetLayout(
modifier = Modifier.fillMaxSize(),
sheetState = bottomSheetState,
sheetContent = {
    ...
})

When I call bottomSheetState.show() and immediately press the physical back button, it navigates back to the previous screen, but the ModalBottomSheetLayout does not close. At that moment, checking bottomSheetState.isVisible returns false. From my understanding, when calling bottomSheetState.show(), the ModalBottomSheetLayout slides up from the bottom, but bottomSheetState.isVisible does not change until the animation completes. How should I handle the back event in this situation?


Solution

  • You can use targetValue instead of isVisible.

    The target value the state will settle at once the current interaction ends, or the currentValue if there is no interaction in progress.

    According to the documentation, targetValue is specifically designed for this use case. It returns the currentValue if the sheet is not animating, and the future ModalBottomSheetValue if the sheet is in the process of animating.

    You can check if targetValue == ModalBottomSheetValue.Expanded because you want to close the sheet if it is either animating to the Expanded state or is currently in the Expanded state.

    BackHandler {
        if (bottomSheetState.targetValue == ModalBottomSheetValue.Expanded) {
            scope.launch { bottomSheetState.hide() }
        } else {
            // TODO: Handle back press
        }
    }