Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass conditional parameter in Jetpack Compose?

I want to hide the navigationIcon but when I pass null or Unit the icon space remains visible, as can be seen in the image below.

Menu preview

@Composable
fun DefaultScaffold(
    title: String? = null,
    icon: ImageVector? = null,
    content: @Composable() () -> Unit
) {
    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    if (title != null) {
                        Text(text = "My Title")
                    }
                },
                navigationIcon = {
                    if (icon != null) {
                        IconButton(
                            onClick = {}
                        ) {
                            Icon(imageVector = Icons.Filled.Close, contentDescription = null)
                        }
                    } else Unit
                }
            )
        }
    ) {
        content()
    }
}
like image 753
Gustavo Faria Avatar asked Sep 12 '25 01:09

Gustavo Faria


2 Answers

Remove the parentheses that surround your conditional statement, then return null instead of Unit when you don't want to show the icon space.

So, it will become

navigationIcon = if (icon != null) {
    {
        IconButton(
            onClick = {}
        ) {
            Icon(imageVector = Icons.Filled.Close, contentDescription = null)
        }
    }
} else null
like image 149
danartillaga Avatar answered Sep 13 '25 15:09

danartillaga


You can use something like

navigationIcon = if (icon != null) {
    { /*... your code ..*/ }
} else null

but the constructor of TopAppBar with title and navigationIcon parameters preserves the slots for a title and the navigation icon. If you check the source code you can find:

if (navigationIcon == null) {
            Spacer(TitleInsetWithoutIcon)
        } else {

You should use the constructor with the content parameter, that has no restriction on content.
Then you can use something like:

    TopAppBar(
        content = {
            Row(Modifier.fillMaxHeight(), verticalAlignment = Alignment.CenterVertically){
                if (icon != null) {
                    IconButton(
                        onClick = {},
                    ) {
                        Icon(imageVector = icon, contentDescription = null)
                    }
                }
                if (title != null) {
                    ProvideTextStyle(value = MaterialTheme.typography.h6) {
                        CompositionLocalProvider(
                            LocalContentAlpha provides ContentAlpha.high,
                        ){
                            Text(text = title)
                        }
                    }
                }
            }
        }
    )

enter image description here enter image description here

like image 31
Gabriele Mariotti Avatar answered Sep 13 '25 15:09

Gabriele Mariotti