I want to change state of ModalBottomSheet from Jetpack Compose in ViewModel.
Here what I do, I have a ViewModel, something like this:
class MyViewModel() {
@ExperimentalMaterialApi
val bottomSheetDialogState = ModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden
)
fun showBottomSheet() {
viewModelScope.launch {
bottomSheetDialogState.show()
}
}
}
and inside Fragment:
@ExperimentalMaterialApi
@Composable
fun ShowUnableToChangeDialog() {
ModalBottomSheetLayout(
sheetState = viewModel.bottomSheetDialogState,
sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
sheetBackgroundColor = Color.White,
sheetContent = {
Box(modifier = Modifier.defaultMinSize(minHeight = 1.dp)) {
Column {
}
}
}
) { }
}
and when I call showBottomSheet()
I catch this exception:
java.lang.IllegalStateException: A MonotonicFrameClock is not available in this CoroutineContext. Callers should supply an appropriate MonotonicFrameClock using withContext. at androidx.compose.runtime.MonotonicFrameClockKt.getMonotonicFrameClock(MonotonicFrameClock.kt:114) at androidx.compose.runtime.MonotonicFrameClockKt.withFrameNanos(MonotonicFrameClock.kt:85) at androidx.compose.animation.core.SuspendAnimationKt.callWithFrameNanos(SuspendAnimation.kt:286) at androidx.compose.animation.core.SuspendAnimationKt.animate(SuspendAnimation.kt:229) at androidx.compose.animation.core.Animatable$runAnimation$2.invokeSuspend(Animatable.kt:291) at androidx.compose.animation.core.Animatable$runAnimation$2.invoke(Unknown Source:8) at androidx.compose.animation.core.Animatable$runAnimation$2.invoke(Unknown Source:2) at androidx.compose.animation.core.MutatorMutex$mutate$2.invokeSuspend(InternalMutatorMutex.kt:119) at androidx.compose.animation.core.MutatorMutex$mutate$2.invoke(Unknown Source:8) at androidx.compose.animation.core.MutatorMutex$mutate$2.invoke(Unknown Source:4) at kotlinx.coroutines.intrinsics.UndispatchedKt.startUndispatchedOrReturn(Undispatched.kt:89)
I tried to use other coroutine scopes, for example with Dispatcher.Main and etc, but exception is still the same. How can I fix it?
CodePudding user response:
It needs to be called within the scope of Composition.
Check please this link: https://developer.android.com/jetpack/compose/side-effects#remembercoroutinescope