I know its not possible to call composable functions inside onClick. @Composable invocations can only happen from the context of a @Composable function
Compose version - alpha06
But I'm stuck with the below requirement. The requirement is, Call a server api call inside an onClick.
LazyColumnFor(items = list) { reports ->
Box(Modifier.clickable(
onClick = {
//API call
val liveDataReportsDetails =
viewModel.getReportDetails("xxxx")
LiveDataComponentForReportsDetails(liveDataReportsDetails)
}
)) {
ReportListItem(
item = reports
)
}
}
mutableStateOf creates an observable MutableState<T> , which is an observable type integrated with the compose runtime. interface MutableState<T> : State<T> { override var value: T. } Any changes to value will schedule recomposition of any composable functions that read value .
A LazyColumn is a vertically scrolling list that only composes and lays out the currently visible items. It's similar to a Recyclerview in the classic Android View system.
Scaffold provides a slot for a floating action button. You can use the floatingActionButton slot and a FloatingActionButton : Scaffold(
Directly in jetpack compose does not support recycler view like the android app.
So you're right, composable functions cannot be called from within onClicks from either a button or a modifier. So you need to create a value like:
private val showDialog = mutableStateOf(false)
When set to true you want to invoke the composable code, like:
if(showDialog.value) {
alert()
}
Alert being something like:
@Composable
fun alert() {
AlertDialog(
title = {
Text(text = "Test")
},
text = {
Text("Test")
},
onDismissRequest = {
},
buttons = {
Button(onClick = { showDialog.value = false }) {
Text("test")
}
}
)
}
Now finish with changing the boolean where intended, like:
Box(Modifier.clickable(
onClick = {
showDialog.value = true
}
))
I hope this explanation helps, of course the value doesn't have to be a boolean, but you get the concept :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With