androidandroid-jetpack-composeandroid-jetpack-compose-material3

Jetpack Compose ModalBottomSheet always showing


The ModalBottomSheet seems to be showing by default although it should actually be hidden (rememberModalBottomSheetState initiates the state with an initialValue : SheetValue = Hidden). Clearly missing something here.

val bottomSheetState = rememberModalBottomSheetState()
ModalBottomSheet(
    onDismissRequest = { /*TODO*/ },
    sheetState = bottomSheetState,
    containerColor = Color.White,
) {
    Text(text = "Why am I showing?", color = Color.Black)
}

calling bottomSheetState.hide() also doesn't seem to have any effect.

Using Jetpack Compose BOM 2023.06.00 but getting the same behaviour on 2023.05.01.


Solution

  • Finally figured this out! The new ModalBottomSheet shows conditionally, so something like this should work:

    val openBottomSheet = rememberSaveable { mutableStateOf(false) }
    val bottomSheetState = rememberModalBottomSheetState()
    
    if (openBottomSheet) {
      ModalBottomSheet(
        onDismissRequest = { openBottomSheet = false },
        sheetState = bottomSheetState,
        containerColor = Color.White,
      ) {
        Text(text = "Why am I showing?", color = Color.Black)
      }
    }