Home > Net >  Composable invocations can only happen from the context of a @Composable function
Composable invocations can only happen from the context of a @Composable function

Time:03-19

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

CodePudding user response:

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.

  • Related