我需要使用协程上下文来处理代码中的 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中执行上下文?
答案 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 使用协程,因此我们需要应用合适的 CoroutineScope
。 rememberCoroutineScope()
会给你一个范围,只要你的作品的这个分支以某种形式存在。