<https://developer.android.com/develop/ui/compose/...
# compose
v
https://developer.android.com/develop/ui/compose/components/bottom-sheets Is there any reason behind using a separate
mutableState
for bottomSheet When we can directly call
show()/hide()
on the SheetState and add it to the composable when
bottomSheetState.isVisible
instead of checking our own mutable state?
s
Using a separate
mutableStateOf
for the
ModalBottomSheet
visibility is more about clarity and control over its presence in the UI. Directly using `show()`/`hide()` on
SheetState
changes its appearance/animation but doesn’t inform Compose to add or remove the sheet from the UI's structure.
If your approach is to use
if (sheetState.isVisible) { ModalBottomSheet(...) }
, indeed, the
ModalBottomSheet
will be added or removed from the composition tree based on its visibility. However, remember that
sheetState
remains within the parent's composition scope. I haven't found a way to explicitly "un-remember" something from memory. By "explicitly", I mean without using logical branches
(if/else)
, which I consider to be implicit control.
My usual method for managing bottom sheets looks like this:
Copy code
var showBottomSheet by remember { mutableStateOf(false) }
if (showBottomSheet) {
    val sheetState = rememberModalBottomSheetState()
    ModalBottomSheet(
        onDismissRequest = { showBottomSheet = false },
        sheetState = sheetState
    )
}
// To show the bottom sheet, I simply set `showBottomSheet` to true.
This approach ensures that when the bottom sheet is not visible, it's removed from the composition tree. Importantly, its state is also cleared from the parent's memory.