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.
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.
On button click, this will show the Text in case it is not shown, and will hide the Text in case it is shown.