DatePicker in Kotlin Compose Multiplatform KMP KMM

In today’s tutorial, we will learn how to integrate DatePicker in Kotlin Compose Multiplatform (KMP/KMM) for both Android and iOS platforms, specifically for native use. In this guide, we will integrate Android’s native Material DatePicker and iOS native UIDatePicker using expect/actual functions.

DatePicker in Kotlin Compose Multiplatform KMP KMM

DatePicker in Kotlin Compose Multiplatform KMP KMM

In a mobile application, DatePicker is an essential UI component that allows users to select any date in the easiest possible way. In Compose Multiplatform, we can easily use platform-specific code, which will enable us to integrate platform-specific UI components. If your app opens on an Android device, it will invoke the native Android component. If your app begins on iOS, it will interact with the native iOS component. But after selecting any data from that component, it syncs that data into the Compose Multiplaform application. We will learn step by step how to implement a DatePicker in Kotlin Compose Multiplatform (KMP/KMM).

Start coding for the app:

1. Android Specific DatePicker Implementation:

1. Open your project’s
APP -> composeApp -> src -> androidMain -> kotlin -> packageName -> MainActivity.kt file.

2. Implement pickDate() method in this file.

Code explanation:

  1. pickDateFunction Declaration: Defines an actual fun pickDate(context: Any?, onDatePicked: (String) -> Unit) to implement the Android-specific date picker for the expect declaration in shared code.
  2. Context Check: Uses if (context !is Context) return to exit the function if the provided context is not an Android Context, ensuring type safety.
  3. Calendar Instance: Creates a Calendar object with Calendar.getInstance() to retrieve the current date and time.
  4. Year Extraction: Gets the current year using calendar.get(Calendar.YEAR) for initializing the date picker.
  5. Month Extraction: Retrieves the current month using calendar.get(Calendar.MONTH) (0-based, e.g., 0 for January).
  6. Day Extraction: Obtains the current day of the month with calendar.get(Calendar.DAY_OF_MONTH) for the date picker’s default date.
  7. DatePickerDialog Creation: Instantiates a DatePickerDialog with the provided context, a listener for date selection, and the current year, month, and day.
  8. Date Selection Listener: Defines a lambda { _, selectedYear, selectedMonth, selectedDay -> … } that formats the selected date as “dd/MM/yyyy” by combining selectedDay, selectedMonth + 1 (to adjust for 0-based months), and selectedYear.
  9. Callback Invocation: Calls onDatePicked(date) to pass the formatted date string to the shared code’s callback function.
  10. Show Dialog: Invokes.show() on the DatePickerDialog to display the Material Design date picker to the user.

3. We also have to pass Context(this) in the App component in the MainActivity.kt file.

Complete source code of the MainActivity.kt file after adding the Date Picker native Android code:

2. iOS Specific DatePicker Implementation:

1. Open your project’s
APP -> composeApp -> src -> iosMain -> kotlin -> packageName -> pickDate.kt file.

2. Creating the pickDate() method for the native iOS Date Picker component.

Code explanation:

  1. Function Declaration: Defines an actual fun pickDate(context: Any?, onDatePicked: (String) -> Unit) to implement the iOS-specific date picker for the expect declaration in shared code.
  2. UIDatePicker Creation: Initializes a UIDatePicker and configures it using an apply block to set its properties.
  3. DatePicker Mode: Sets datePickerMode = UIDatePickerMode.UIDatePickerModeDate to configure the picker for selecting dates only (no time).
  4. DatePicker Style: Sets preferredDatePickerStyle = UIDatePickerStyle.UIDatePickerStyleWheels to use a wheel-style interface for the date picker.
  5. Constraints Disabled: Sets translatesAutoresizingMaskIntoConstraints = false to allow manual constraint setup for the date picker’s layout.
  6. Alert Controller Creation: Creates a UIAlertController with title “Pick a Date,” a placeholder message with newlines for spacing, and UIAlertControllerStyleAlert style.
  7. Add DatePicker to Alert: Adds the UIDatePicker as a subview to the alert controller’s view for display within the alert.
  8. Center X Constraint: Aligns the date picker’s horizontal center to the alert’s center using centerXAnchor.constraintEqualToAnchor.
  9. Top Constraint: Positions the date picker 10 points from the alert’s top edge using topAnchor.constraintEqualToAnchor.
  10. Width Constraint: Sets the date picker’s width to the alert’s width minus 20 points using widthAnchor.constraintEqualToAnchor for a balanced layout.
  11. Activate Constraints: Enables the constraints by setting .active = true for center, top, and width anchors to position the date picker correctly.
  12. Done Action Creation: Adds a “Done” button to the alert using UIAlertAction with UIAlertActionStyleDefault style.
  13. Date Formatter Setup: Creates an NSDateFormatter with dateFormat = “dd-MM-yyyy” to format the selected date (e.g., “24-06-2025”).
  14. Date Selection: Converts the datePicker.date to a string using the formatter and assigns it to selectedDate.
  15. Callback Invocation: Calls onDatePicked(selectedDate) to pass the formatted date string to the shared code’s callback.
  16. Present Alert: Displays the alert controller with a date picker using presentViewController, with an animated transition for a smooth effect.

3. We have to pass null at the place of context in the App. Open your project’s :

APP -> composeApp -> src -> iosMain -> kotlin -> packageName -> MainViewController.kt file.

3. Common DatePicker Implementation:

1. Open your project and create a file:
APP -> composeApp -> src -> commonMain -> kotlin -> packageName -> date_picker.kt file.

Code explanation:

  1. Expect Function Declaration: Defines expect fun pickDate(context: Any?, onDatePicked: (String) -> Unit) in the shared module to declare a platform-agnostic function signature.
  2. Function Parameters: Includes context: Any? for platform-specific context (e.g., Android Context or null for iOS) and
  3. onDatePicked: (String) -> Unit as a callback to return the selected date as a string.
  4. Purpose of Expect: Signals that platform-specific implementations (actual) for Android and iOS will provide the exact behavior, ensuring shared code can call pickDate uniformly.

4. Common DatePicker Implementation in App.kt file:

Screenshot on an Android device:

Screenshot on an iOS device:

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 *