Reputation: 11
I am sheer beginner in Jetpack Compose library of Kotlin and I was making a simple UI to practice. I Made a Button and I wanted to display a text in the event of someone clicking on code but I got an error
Button( onClick = {
Text("Hello World!")}{
Text("Click Me")}
error: "@Composable invocations can only happen from the context of a @Composable function"
How do I fix it
I was expecting when someone click on the button it shows Hello world under it.
Upvotes: 1
Views: 534
Reputation: 70
A composable can be called from another composable but not a lambda. Hence you can not add Text() in onClick of Button composable.
If you want to display the text upon button click, add the Composable to the composable hierarchy when the button is clicked, that is show the Text composable conditionally. So, add the Text composable in an if block.
Upon clicking the button to show or hide the Text, change the value of the shouldShowText variable. For the value to reflect in the UI or for the Composable to re-compose based on the value change, use mutableStateOf. Read about the State here.
var shouldShowText: Boolean by remember { mutableStateOf(false) }
Column (
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Button(
onClick = { shouldShowText = !shouldShowText },
modifier = Modifier.wrapContentSize()
) {
Text(text = "Click here")
}
if (shouldShowText) {
Text(text = "Hello World!")
}
}
On button click, this will show the Text in case it is not shown, and will hide the Text in case it is shown.
Upvotes: 0
Reputation: 61
I'm not sure if you want 1. the text label of your button to change, or 2. show a Toast when the Button is clicked.
In general, onClick is a lambda function, and not a composable. You can onlytrigger a state change or an event in that.
For 1, since Compose follows a declarative paradigm, you need to change the state when the button is pressed.
var textValue by remember { mutableStateOf("Default value") }
Button(
onClick = { textValue = "Hello World" }
) {
Text(text = textValue)
}
For 2, you can just show a Toast when onClick is pressed.
val context = LocalContext.current
Button(
onClick = { Toast.makeText(context, "Hello World", Toast.LENGTH_SHORT).show() }
)
Upvotes: 1
Reputation: 43
Try like this
Button( onClick = {
}**
The idea is that I have a Text Composable with the value of the textClick variable and I change only the variable's state when I click
Upvotes: 0