Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack Compose - How can we call a @Composable function inside an onClick()

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
        )
    }
}
like image 531
DSP Avatar asked Jan 09 '21 10:01

DSP


People also ask

What is mutableStateOf in jetpack compose?

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 .

What is LazyColumn in jetpack compose?

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.

What is scaffold in jetpack compose?

Scaffold provides a slot for a floating action button. You can use the floatingActionButton slot and a FloatingActionButton : Scaffold(

Does jetpack compose use Recyclerview?

Directly in jetpack compose does not support recycler view like the android app.


1 Answers

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 :).

like image 148
jobbert Avatar answered Oct 16 '22 08:10

jobbert