ursus
10/17/2025, 11:57 PMmaterial3 bottom sheets based on view model state?ursus
10/18/2025, 12:00 AMenum class SheetType { Foo, Bar }
class SheetViewModel : ViewModel() {
private val _sheet = MutableStateFlow<SheetType?>(null)
val sheet: StateFlow<SheetType?> = _sheet.asStateFlow()
fun show(type: SheetType) { _sheet.value = type }
fun hide() { _sheet.value = null }
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EnumBottomSheetHost(
viewModel: SheetViewModel = androidx.lifecycle.viewmodel.compose.viewModel()
) {
val sheet by viewModel.sheet.collectAsStateWithLifecycle()
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
LaunchedEffect(sheet) {
if (sheet == null) {
sheetState.hide()
} else {
sheetState.show()
}
}
ModalBottomSheet(
sheetState = sheetState,
onDismissRequest = { viewModel.hide() }
) {
when (sheet) {
SheetType.Foo -> Text("Foo content", Modifier.padding(24.dp))
SheetType.Bar -> Text("Bar content", Modifier.padding(24.dp))
null -> Spacer(Modifier.height(1.dp))
}
}
}
This is what I have, but not sure if idiomatic.
Also I'd like to hide first and only then show if the modal changes from Foo to Bar