I try to make custom ModalBottomSheet() with this code:
Box(modifier = Modifier.fillMaxSize()) { Box( modifier = Modifier .fillMaxSize() .background(Color.Black.copy(alpha = 0.45f)) ) AnimatedVisibility( modifier = Modifier.align(Alignment.BottomCenter), visible = visible, enter = slideInVertically(), exit = slideOutVertically() ) {...
I would like the exit animation to run when the external visible state changes to false, while also unmounting the entire composable from the view. Similarly, when visible changes to true, I would like the composable to be mounted and the enter animation to run.
If you immediately remove the composable when visible = false, Compose has no time to play the exit animation.
External state controls requested visibility
Internal state keeps the composable mounted until exit animation finishes
A more robust approach uses MutableTransitionState instead of hardcoded delays:
This is the preferred Compose solution because it automatically keeps the composable mounted until the exit transition fully completes.
@Composable
fun CustomBottomSheet(
visible: Boolean,
content: @Composable () -> Unit
) {
val state = remember {
MutableTransitionState(false)
}
state.targetState = visible
if (state.currentState || state.targetState) {
AnimatedVisibility(
visibleState = state,
enter = slideInVertically(
initialOffsetY = { it }
),
exit = slideOutVertically(
targetOffsetY = { it }
)
) {
content()
}
}
}
Sweta Jain