Search code examples
androidkotlintabsandroid-jetpack-composeandroid-jetpack-compose-material3

text and icon parameters in a Tab don't allow composable invocations


In this code, in the text parameter, I get the error:

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

The same happens to me with icon:

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

If I delete the text parameter and the icon parameter, the code works correctly, but I want to display a text and an icon in each tab. I have imported androidx.compose.material3.Tab and the dependency implementation(platform("androidx.compose:compose-bom:2024.04.01")).

PrimaryTabRow(
    selectedTabIndex = selectedTabIndex
) {
    tabItems.forEachIndexed { index, item ->
        Tab(
            selected = (selectedTabIndex == index),
            onClick = {
                selectedTabIndex = index
            },
            text = { Text(text = item.titulo) },
            icon = {
                Icon(
                    imageVector = if (index == selectedTabIndex) item.selecIcon else item.unselecIcon,
                    contentDescription = item.titulo
                )
            }
        ) {

        }
    }
}

Solution

  • You need to remove the empty lambda (the curly braces { }) after Tab(...).

    The reason is that there are two Tab composables, one with a parameter text and one with a content lambda. You tried to use both parameter so the compiler couldn't decide which of the two composables to choose and for the time being takes none.

    For the rest of the code it assumes there will be some function that has all the parameters you specified, but it won't know which type they are so the text and the icon lambda are just assumed to be simple lambdas and at first glance it looks ok. But the Text compsable and the Icon composable you use in those lambdas detect that they are not called from a composable lambda, hence your error.

    The error you stumbled over is just following from the first error that Tab couldn't be found. If you would have started with that by the time you would have looked at the following errors they would have already vanished.