我想在 ViewModel 中從 Jetpack Compose 更改 ModalBottomSheet 的狀態。
我在這里做什么,我有一個 ViewModel,像這樣:
class MyViewModel() {
@ExperimentalMaterialApi
val bottomSheetDialogState = ModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden
)
fun showBottomSheet() {
viewModelScope.launch {
bottomSheetDialogState.show()
}
}
}
和片段內部:
@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 {
}
}
}
) { }
}
當我打電話時,showBottomSheet()我發現了這個例外:
java.lang.IllegalStateException:此 CoroutineContext 中沒有 MonotonicFrameClock。呼叫者應使用 withContext 提供適當的 MonotonicFrameClock。在 androidx.compose.runtime.MonotonicFrameClockKt.getMonotonicFrameClock(MonotonicFrameClock.kt:114) 在 androidx.compose.runtime.MonotonicFrameClockKt.withFrameNanos(MonotonicFrameClock.kt:85) 在 androidx.compose.animation.core.SuspendSpendFrameClock(MonotonicFrameClock.kt:114) :286) 在 androidx.compose.animation.core.SuspendAnimationKt.animate(SuspendAnimation.kt:229) 在 androidx.compose.animation.core.Animatable$runAnimation$2.invokeSuspend(Animatable.kt:291) 在 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。
我嘗試使用其他協程范圍,例如 Dispatcher.Main 等,但例外仍然相同。我該如何解決?
uj5u.com熱心網友回復:
它需要在 Composition 的范圍內呼叫。
請檢查此鏈接:https : //developer.android.com/jetpack/compose/side-effects#remembercoroutinescope
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/396210.html
標籤:安卓 科特林 android-jetpack-compose
