ModalDrawer 需要协程上下文来更改状态隐藏和显示喷气背包组合

时间:2021-02-27 19:32:20

标签: android kotlin android-jetpack android-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中执行上下文?

1 个答案:

答案 0 :(得分:3)

调用 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() 会给你一个范围,只要你的作品的这个分支以某种形式存在。