DSP
DSP

Reputation: 435

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
        )
    }
}

Upvotes: 42

Views: 29065

Answers (1)

jobbert
jobbert

Reputation: 3497

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

Upvotes: 54

Related Questions