Ask Your Question

Revision history [back]

In Jetpack Compose, the animation of the bottom sheet is achieved using the AnimatedVisibility and Modifier.offset functions.

First, we set up the bottom sheet layout with its initial state using a Scaffold composable:

Scaffold(
    bottomSheet = {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
        ) {
            // content of the bottom sheet
        }
    }
) {
    // rest of the screen content
}

To animate the visibility of the bottom sheet, we wrap the Box composable inside an AnimatedVisibility composable and set its visibility state:

var bottomSheetVisible by remember { mutableStateOf(false) }

Scaffold(
    bottomSheet = {
        AnimatedVisibility(
            visible = bottomSheetVisible,
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
        ) {
            Box(
                modifier = Modifier
                    .background(Color.White)
            ) {
                // content of the bottom sheet
            }
        }
    }
) {
    // rest of the screen content
}

Finally, to animate the position of the bottom sheet as it appears or disappears, we add a Modifier.offset to the Box composable and update its value based on the visibility state:

val sheetOffset = 200.dp

Scaffold(
    bottomSheet = {
        AnimatedVisibility(
            visible = bottomSheetVisible,
            modifier = Modifier
                .fillMaxWidth()
                .height(sheetOffset)
                .offset {
                    IntOffset(
                        x = 0,
                        y = if (bottomSheetVisible) 0 else sheetOffset.roundToPx()
                    )
                }
        ) {
            Box(
                modifier = Modifier
                    .background(Color.White)
            ) {
                // content of the bottom sheet
            }
        }
    }
) {
    // rest of the screen content
}

This will animate the bottom sheet in and out of the screen with a slide-up and slide-down motion.