Hide badge in BadgeBox in Jetpack Compose

Viewed 1115
BadgeBox(badgeContent = { Text("8") }) {
    Icon(
        Icons.Filled.Favorite,
        contentDescription = "Favorite"
    )
}

I have a BadgeBox like this. But if the value is 0, I want to badge to disappear. If I pass null to badgeContent, the circle still shows but with nothing in it.

How do I hide it completely?

1 Answers

Since 1.1.0 Badge has been moved from BadgeBox, so if you're using Compose version 1.1.x or newer, you can use it as follows:

BadgedBox(
    badge = {
        if (count > 0) {
            Badge {
                Text("$count")
            }
        }
    }
) {
    Icon(
        Icons.Filled.Favorite,
        contentDescription = "Favorite"
    )
}

Solution for version 1.0.x.

You can specify backgroundColor to transparent color when you don't need to display the badge:

BadgeBox(
    badgeContent = {
        if (count > 0) {
            Text("$count")
        }
    },
    backgroundColor = if (count > 0) MaterialTheme.colors.error else Color.Transparent
) {
    Icon(
        Icons.Filled.Favorite,
        contentDescription = "Favorite"
    )
}
Related