Notification Badges in Kotlin Compose Multiplatform KMP KMM

In today’s tutorial, we will learn about Notification badges in Kotlin Compose Multiplatform (KMP/KMM) for Android, iOS, and web platforms. We will be using the BadgeBox and Badge components.

Notification Badges in Kotlin Compose Multiplatform KMP KMM

Notification Badges in Kotlin Compose Multiplatform KMP KMM:

Badges are a vital UI component in KMP that displays notification counts in applications. KMP offers custom Badges that can be customized and directly integrated as a separate UI component with all the properties to modify it. We can display notification counts or any other numerical updates in the Badges, as they can be easily controlled using the State.

Start coding for the app:

1. Creating a State named itemCount with a default value of zero.

2. Creating BadgedBox with Email Icon.

Code explanation:

  1. BadgedBox wraps an Icon (email) with a Badge.
  2. The Badge() is empty, displaying a simple red dot.

Screenshot:

Notification badge without number

3. Creating a customised Badge with a number value:

Code explanation:

  1. BadgedBox: Starts a Jetpack Compose component that positions a badge over content, such as an icon, using badge and content lambdas.
  2. Badge Lambda: Defines the badge’s appearance and behavior in a lambda for the badge parameter.
  3. If Condition (itemCount > 0): Checks if itemCount exceeds 0 to show the badge only for positive counts.
  4. Badge Composable: Creates a badge with a red background and white text, displayed when itemCount is positive.
  5. Text Inside Badge: Shows itemCount as a centered string with 12sp font size within the badge.
  6. Icon Composable: Displays a shopping cart icon with a “Shopping cart” accessibility description.
  7. Overall Functionality: Combines icon and badge, displaying the badge over the icon when itemCount > 0, and updates dynamically.

Screenshot:

Notification Badges in Kotlin Compose Multiplatform KMP KMM

Complete source code of App.kt file:

Screenshot on an iOS device:

Notification badge in iOS KMP KMM

Screenshot on an Android device:

Notification badge in Android in KMP KMM

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *