I need to use a coroutine context to work with modalState.show()
or modalState.hide()
in my code
@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) {}
}
Before it was working and now it requires a coroutine context, how to execute the context within jetpack compose?
Call rememberCoroutineScope()
, hold onto it in a variable, and use that to launch()
your show()
and hide()
calls:
@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, the suspend
call is used because the animation APIs in Compose UI are using coroutines, so we need to apply a suitable CoroutineScope
. rememberCoroutineScope()
will give you a scope that is good for as long as this branch of your composition is around in some form.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.