我需要在代码中使用协程上下文来处理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中执行上下文?
发布于 2021-02-28 03:36:40
调用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()就会给你一个很好的作用域。
https://stackoverflow.com/questions/66402720
复制相似问题