I have found that
val list: List<@Composable ()-> Unit> = listOf({Text("Cat")}, {Text("Dog")})
works, but
val list: List<@Composable ()-> Unit> = listOf({Text("Cat")}) + listOf({Text("Dog")})
produces the error "@Composable invocations can only happen from the context of a @Composable function" on the first Text().
Why is it that adding lists works fine with things like
val list: List<String> = listOf("Cat") + listOf("Dog")
but doesn't seem to work with Composables? Is there a way how I can add lists of Composables to each other?
The difference in behavior between the two scenarios is related to how Jetpack Compose handles the
@Composablefunctions and the context in which they are invoked.In the first scenario:
Both
Text("Cat") and Text("Dog")are wrapped in @Composable lambda expressions within the list. When you use the list directly, the lambda expressions are invoked within the context of a @Composable function.In the second scenario:
Here, you are using the
+operator to concatenate two lists. The resulting list contains two@Composablelambda expressions, but they are not automatically invoked within a@Composablecontext.To Better understand, try with this example