I want to hide the bottom sheet from inside a ViewModel (after a backend call succeeded).
To do this, I need to emit a
StateFlow
from the ViewModel which contains a boolean property
showBottomSheet
.
In my screen's composable, I can then remember (and reinitialize) the bottom sheet state like this:
val modalBottomSheetState = rememberModalBottomSheetState(if (screenState.showBottomSheet) Expanded else Hidden)
That takes care of hiding the bottom sheet.
But how do I keep the
showBottomSheet
state in the ViewModel synchronized with the composable, when e.g. the user swipes down the bottom sheet? For this I included a callback in the composable:
onBottomSheetDismissed
.
I called this callback in the
confirmStateChange
lambda parameter of `rememberModalBottomSheetState()`:
// Composable
val modalBottomSheetState = rememberModalBottomSheetState(
initialValue = if (screenState.showBottomSheet) Expanded else Hidden,
confirmStateChange = {
onBottomSheetDismissed()
true
}
)
// ViewModel
val screenState: StateFlow<ScreenState> = _screenState.asStateFlow()
private val _screenState: MutableStateFlow<ScreenState>
fun onBottomSheetDismissed() {
_screenState.update { it.copy(showBottomSheet = false) }
}
But it appears that this callback is called very early in the dragging process, and my
showBottomSheet
variable in the ViewModel gets reset to
false
as soon as the user even drags the bottom sheet one pixel down and the bottom sheet immediately disappears (see video in thread)
Is there a better way to handle opening/closing the bottom sheet from a viewmodel and keeping the state synchronized between the two?