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

Composable invocations can only happen from the context of a composable function. Composable functions are special functions in Jetpack Compose that allow you to write reusable UI components. They are annotated with the @Composable annotation.

When you use composable functions, you can only call other composable functions from within them. This restriction ensures that the UI can be efficiently and easily composed, updated, and rendered by the Compose framework.

Here’s an example to illustrate this concept:


import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.Text
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier

@Composable
fun MyComposableFunction() {
    // This is a composable function
    Column(
        modifier = Modifier.fillMaxWidth().wrapContentHeight().background(Color.LightGray),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "Hello, World!",
            style = TextStyle(
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Center
            )
        )
    }
}

@Composable
fun AnotherComposableFunction() {
    // This is also a composable function
    Box(modifier = Modifier.fillMaxSize().background(Color.White)) {
        MyComposableFunction() // Call to a composable function is allowed
    }
}

fun main() {
    // This is NOT a composable function
    AnotherComposableFunction() // Calling a composable function from here is not allowed
}
  

In the code above, we define two composable functions: MyComposableFunction and AnotherComposableFunction. The MyComposableFunction function creates a composable UI component that displays a centered text with a light gray background. The AnotherComposableFunction function creates a composable UI component that displays a white background and calls the MyComposableFunction function.

Note that the main function is not a composable function, so it cannot directly call or invoke a composable function like AnotherComposableFunction. This would result in a compilation error. Composable invocations can only happen from the context of a composable function, which is why we cannot call composable functions from non-composable functions.

Read more interesting post

Leave a comment