@composable invocations can only happen from the context of a @composable function

Explanation:

The error message indicates that @composable invocations can only occur within the context of a @composable function.

A composable function is a function that is annotated with the @Composable annotation in Jetpack Compose, which is used to build UI components. These functions can only be called from other composable functions or from the top-level scope of your UI composition.

Here’s an example to illustrate:

{@literal @Composable}
  fun MyComposableFunction() {
      Text(text = "Hello, Jetpack Compose!")
  }
  
  // Calling the composable function within the context of another composable function
  {@literal @Composable}
  fun MyOuterComposable() {
      MyComposableFunction()
  }
  
  // Incorrect usage outside a composable function (will result in the mentioned error)
  fun someFunction() {
      MyComposableFunction() // Error: Invoking composable from non-composable function
  }
  

In the example above, MyComposableFunction() is a composable function that displays a simple text component. It is called within the MyOuterComposable() function, which is also a composable function. This is the correct usage.

However, if you try to call MyComposableFunction() from a regular non-composable function like someFunction(), you will encounter the mentioned error message.

To fix this error, ensure that you are calling the composable function within the context of another composable function or from the top-level of your UI composition hierarchy.

Related Post

Leave a comment