6

I have a composable function that i need to call after clicking a button but it keeps showing an error that composables cannot be executed from button clicks , can anyone please guide me to solve this issue Thank you

  • This is my code
  Box(contentAlignment = Alignment.Center) {
               Button(onClick = {
                    // This is a composable function that i need to call
                    SignUpNewUser(email,fullName,country,password)
                }
                ,modifier = Modifier
                       .width(200.dp)
                       .background(color = Color.DarkGray)) {
                Text(text = "Sign Up",style = TextStyle(color = Color.White,fontWeight = FontWeight.Bold))
            }
        }

1 Answer 1

10

You can only add a @Composable view to another @Composable view.

onClick is not marked @Composable, so you get this warning. You can only change the state with onClick.

For example, you can create a flag and display the UI depending on that flag:

var signUp by remember { mutableStateOf(false) }
if (signUp) {
    SignUpNewUser(email, fullName, country, password)
} else {
    Box(contentAlignment = Alignment.Center) {
        Button(onClick = {
            signUp = true
        }, modifier = Modifier
            .width(200.dp)
            .background(color = Color.DarkGray)) {
            Text(text = "Sign Up", style = TextStyle(color = Color.White, fontWeight = FontWeight.Bold))
        }
    }
}

I suggest you start with this youtube video which explains the basic principles of when you need to use state in compose. You can continue deepening your knowledge with state in Compose documentation.

Another option would be to use Compose Navigation.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.