Home > Software design >  TopAppBar @composable invocations can only happen from the context of an @composable function
TopAppBar @composable invocations can only happen from the context of an @composable function

Time:12-04

I was trying to add TopAppBar. When I tried to add the following code, I got

@composable invocations can only happen from the context of an @composable function** error.

@Composable
fun appTopBar(name: String) {
    val scaffoldState = rememberScaffoldState(rememberDrawerState(DrawerValue.Closed))
    Scaffold(
        scaffoldState = scaffoldState,
        topBar = {
            TopAppBar(
                title = { Text(text = name) },
                backgroundColor = MaterialTheme.colors.primary
            ) {
                
            }
        }, content = {

        })
}

But when I tried to delete the last {} of TopAppBar, the error was resolved. Like the following code.

@Composable
fun appTopBar(name: String) {
    val scaffoldState = rememberScaffoldState(rememberDrawerState(DrawerValue.Closed))
    Scaffold(
        scaffoldState = scaffoldState,
        topBar = {
            TopAppBar(
                title = { Text(text = name) },
                backgroundColor = MaterialTheme.colors.primary
            )
        }, content = {

        })
}

My question is what is the difference between TopAppBar(){} and TopAppBar(). {} is generated automatically by the Android Studio.

CodePudding user response:

Kotlin trailing lambda can only be used with the last lambda argument.

When you're specifying it for TopAppBar, the only possible variant doesn't have title argument:

@Composable
fun TopAppBar(
    modifier: Modifier = Modifier,
    backgroundColor: Color = MaterialTheme.colors.primarySurface,
    contentColor: Color = contentColorFor(backgroundColor),
    elevation: Dp = AppBarDefaults.TopAppBarElevation,
    contentPadding: PaddingValues = AppBarDefaults.ContentPadding,
    content: @Composable RowScope.() -> Unit
) ...

On the other hand, TopAppBar which accepts title doesn't have a last lambda argument:

fun TopAppBar(
    title: @Composable () -> Unit,
    modifier: Modifier = Modifier,
    navigationIcon: @Composable (() -> Unit)? = null,
    actions: @Composable RowScope.() -> Unit = {},
    backgroundColor: Color = MaterialTheme.colors.primarySurface,
    contentColor: Color = contentColorFor(backgroundColor),
    elevation: Dp = AppBarDefaults.TopAppBarElevation
) ...

It was generated by AS, because of a bug. I've reported it.

  • Related