Home > Back-end >  Compose: custom top bar, render (or not) a navigationIcon based on a nullable callback parameter
Compose: custom top bar, render (or not) a navigationIcon based on a nullable callback parameter

Time:08-18

Given the following code:

@Composable
fun CustomBar(title: String, onBackPressed: (() -> Unit)? = null) {
    TopAppBar(
        title = {
            Text(
                title,
                style = TextStyle(
                    fontFamily = appFontFamily,
                    fontSize = 24.sp,
                    fontWeight = FontWeight(600)
                )
            )
        },
        navigationIcon = {
            if (onBackPressed != null) {
                IconButton(onClick = { onBackPressed() }) {
                    Icon(
                        painterResource(id = drawable.ic_topbar_back),
                        contentDescription = null
                    )
                }
            }
        },
        backgroundColor = Color.White,
        elevation = 0.dp,
        contentColor = MaterialTheme.colors.primary
    )
}

My intention is to:

  • Create a reusable component to add custom TopAppBar in my application
  • I need to provide a title to all bars
  • I optionally can send a callback to react to back presses, if the callback is not null then I want to show the back icon, if the callback is null then no navigationIcon must be rendered

The above code works. The only problem is that if I send a null callback, an empty space is rendered as if Compose is leaving space for a navigationIcon.

What I want to achieve: if I send the parameter onBackPressed as NULL then it should be equals as setting navigationIcon to NULL when creating the TopAppBar.

How can I achieve that? Many Thanks.

CodePudding user response:

navigationIcon is nullable. If you don't want your TopAppBar to have a navigation icon, you have to pass null. Currently, you always pass a non null composable function, which is empty if onBackPressed is null. You have to move your if condition one level up:

navigationIcon = if (onBackPressed == null) null else {
    {
        IconButton(onClick = onBackPressed) {
            Icon(
                painterResource(id = drawable.ic_topbar_back),
                contentDescription = null
            )
        }
    }
}
  • Related