Yoshi
Yoshi

Reputation: 11

Why am I not able to use Text( ) inside Button( )'s onClick ={ }?

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

Answers (3)

Kavyasri K
Kavyasri K

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

codeignitor
codeignitor

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

Mihneas22
Mihneas22

Reputation: 43

Try like this

**val textClick = remember{ MutableStateOf("Hellllooooo Wooorld") }

Text(text = "${textClick.value}")

Button( onClick = {

textClick.value = "This text changed when I clicked"

} {

Text("Click Me")

}**

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

Related Questions