Psijic
Psijic

Reputation: 992

How to pass a nullable variable as a composable?

I want to make a TopAppBar switching its content while navigating. The goal is to use a flag and change the navigationIcon. But I can't pass the Composable/null as a parameter here. The code:

val navIcon = if (viewModel.isBackAvailable) NavIcon { navController.navigateUp() } else null

TopAppBar(navigationIcon = navIcon)// Required:(() → Unit)? Found:Unit?

@Composable
private fun NavIcon(navigate: () -> Unit) {
    IconButton(onClick = navigate) {
        Icon(
            imageVector = Icons.Rounded.ArrowBack,
            contentDescription = stringResource(R.string.navigate_back),
            tint = MaterialTheme.colorScheme.primary
        )
    }
}

I can't pass something like an empty value navigationIcon = {} because it takes its space in this case, I need to use null.

Upvotes: 2

Views: 4602

Answers (1)

Jan Bína
Jan Bína

Reputation: 7208

In your code, navIcon is a result of NavIcon function call, which is unit. You need to have function reference there, you can do that like this:

val navIcon: (@Composable () -> Unit)? = if (viewModel.isBackAvailable) {
    { NavIcon { navController.navigateUp() } }
} else null

Upvotes: 13

Related Questions