0

My IDE is showing that navigationIcon is not a composable function. Other people are doing the same thing. I'm getting this error

@composable invocations can only happen from the context of an @composable function
@Composable
fun AppBar(onClick: () -> Unit){
    TopAppBar(
        title = "Princess World", 
        navigationIcon = { 
            IconButton(onClick = onClick) {
                Icon(imageVector = Icons.Default.Menu, contentDescription = null)
            } 
        },
    ) {}
}

I'm unable to use composable functions inside of title and navigation icon {}

@Composable
fun AppBar(onClick: () -> Unit){
   TopAppBar(title = { }, navigationIcon = { }) {

   }
}
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • 1
    You might consider editing your question and posting which specific `TopAppBar()` function signature you are calling. Not only are there several `TopAppBar()` functions, but there are many versions of Compose. – CommonsWare Nov 12 '22 at 18:01
  • There are 2 and only one with navigationIcon as a parameter. Secondly, all software has many versions. I'm not posting a bug. – Chris Basinger Nov 12 '22 at 18:25

2 Answers2

1

Looks like there are 2 TopAppBar composable that you have to invoke properly with their corresponding parameters.

This one,

@Composable
fun AppBar(onClick: () -> Unit) {
    TopAppBar(
        title = { Text (text = "Princess World") },
        navigationIcon = {
            IconButton(onClick = onClick) {
                Icon(imageVector = Icons.Default.Menu, contentDescription = null)
            }
        }
    ) 
}

calling this one from the API,

@Composable
    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
    ) { … }

or this one,

TopAppBar {

}

calling this from the API

@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
) { … }
z.g.y
  • 5,512
  • 4
  • 10
  • 36
0

You have to remove the final {}:

TopAppBar(
    title = { Text("Princess World") },
    navigationIcon = {
        IconButton(onClick = onClick) {
            Icon(imageVector = Icons.Default.Menu, contentDescription = null)
        }
    }
)

Using the {} you are trying to use the constructor with the attribute content: @Composable RowScope.() -> Unit that doesn't have the title and the navigationIcon attributes.

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841