ModalDrawer 需要协程上下文来更改状态 hide 和 show jetpack compose

ModalDrawer requires coroutine context to change state hide and show jetpack compose

我需要使用协程上下文来处理我代码中的 modalState.show()modalState.hide()

@ExperimentalMaterialApi
@Composable
fun ModalBottomSheetLayoutDemo() {
    val modalState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)

    Button(modifier = Modifier.padding(16.dp), onClick = { modalState.show() }) {
        Text("Show Bottom Sheet")
    }

    ModalBottomSheetLayout(sheetState = modalState, sheetContent = {
        Text(
            modifier = Modifier.padding(start = 8.dp, top = 8.dp),
            text = "Title",
            fontWeight = FontWeight.Bold,
            style = typography.h5
        )
        Text(
            modifier = Modifier.padding(start = 8.dp, top = 8.dp),
            text = "Content example right here :)",
            style = typography.body1
        )
        Row(modifier = Modifier.align(Alignment.CenterHorizontally).padding(8.dp)) {
            Button(modifier = Modifier.padding(end = 8.dp), onClick = { modalState.hide() }) {
                Text("Cancel")
            }
            Button(onClick = { modalState.hide() }) {
                Text("Ok")
            }
        }
    }, sheetElevation = 8.dp) {}
}

之前它可以工作,现在它需要一个协程上下文,如何在 jetpack compose 中执行上下文?

调用 rememberCoroutineScope(),在变量中保留它,然后将其用于 launch() 您的 show()hide() 调用:

@ExperimentalMaterialApi
@Composable
fun ModalBottomSheetLayoutDemo() {
    val modalState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)
    val sillyScope = rememberCoroutineScope()

    Button(modifier = Modifier.padding(16.dp), onClick = { sillyScope.launch { modalState.show() } }) {
        Text("Show Bottom Sheet")
    }

    ModalBottomSheetLayout(sheetState = modalState, sheetContent = {
        Text(
            modifier = Modifier.padding(start = 8.dp, top = 8.dp),
            text = "Title",
            fontWeight = FontWeight.Bold,
            style = typography.h5
        )
        Text(
            modifier = Modifier.padding(start = 8.dp, top = 8.dp),
            text = "Content example right here :)",
            style = typography.body1
        )
        Row(modifier = Modifier.align(Alignment.CenterHorizontally).padding(8.dp)) {
            Button(modifier = Modifier.padding(end = 8.dp), onClick = { modalState.hide() }) {
                Text("Cancel")
            }
            Button(onClick = { sillyScope.launch { modalState.hide() } }) {
                Text("Ok")
            }
        }
    }, sheetElevation = 8.dp) {}
}

AFAICT,使用 suspend 调用是因为 Compose UI 中的动画 API 使用协程,因此我们需要应用合适的 CoroutineScoperememberCoroutineScope() 会给你一个范围,只要你的组合的这个分支以某种形式存在就可以。