Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 300
Psijic Avatar asked Mar 02 '26 18:03

Psijic


1 Answers

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
like image 195
Jan Bína Avatar answered Mar 06 '26 01:03

Jan Bína



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!