Header Ads Widget

Responsive Advertisement

When working with Compose Multiplatform (CMP), you often need to access platform-specific features to enhance user experience. One common requirement is displaying native ⚠️ Alert Dialogs or 🪟 AlertViews on Android and iOS.

show alert dialog native image thumbnail

Here’s how you can implement native alert dialogs while still maintaining a shared codebase using CMP! ✨


Step 1: Set Up Your Compose Multiplatform Project 🔧

Ensure your CMP project is properly set up to target 🤖 Android and 🍎 iOS. If you're starting fresh, follow the official setup guide.


Step 2: Define a Shared API 🤝

Create a shared interface for showing alerts so that your business logic remains platform-agnostic.

Shared Code (🛠️ Kotlin)

Create a file in commonMain module "AlertPresenter.kt"


//AlertPresenter.kt

interface AlertPresenter {
    @Composable
    fun ShowAlert(title: String, message: String, onDismiss: () -> Unit)
}

expect fun getAlertPresenter(): AlertPresenter

    

Step 3: Implement Platform-Specific Alerts 🛠️

Android Implementation 🤖

1. Create a file in androidMain module "AlertPresenter.android.kt"

2. Use the Android ⚠️ AlertDialog class to show native alerts.


//AlertPresenter.android.kt

import android.app.AlertDialog
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext

actual fun getAlertPresenter(): AlertPresenter = AndroidAlertPresenter()

class AndroidAlertPresenter : AlertPresenter {

    @Composable
    override fun ShowAlert(title: String, message: String, onDismiss: () -> Unit) {
        val context = LocalContext.current // Compose's way to get the Android context
        AlertDialog.Builder(context).apply {
            setTitle(title)
            setMessage(message)
            setPositiveButton("OK") { _, _ -> onDismiss() }
            create()
            show()
        }
    }
}

    

iOS Implementation 🍎

1. Create a file in iOSMain module "AlertPresenter.ios.kt"

2. Use 🪟 UIAlertController to show alerts in iOS.


//AlertPresenter.ios.kt

import androidx.compose.runtime.Composable
import platform.UIKit.UIAlertAction
import platform.UIKit.UIAlertActionStyleDefault
import platform.UIKit.UIAlertController
import platform.UIKit.UIAlertControllerStyleAlert
import platform.UIKit.UIApplication

actual fun getAlertPresenter(): AlertPresenter = IOSAlertPresenter()

class IOSAlertPresenter : AlertPresenter {

    @Composable
    override fun ShowAlert(title: String, message: String, onDismiss: () -> Unit) {
        val alertController = UIAlertController.alertControllerWithTitle(
            title,
            message,
            UIAlertControllerStyleAlert
        )

        alertController.addAction(
            UIAlertAction.actionWithTitle("OK", UIAlertActionStyleDefault) {
                onDismiss()
            }
        )

        val rootViewController = UIApplication.sharedApplication.keyWindow?.rootViewController
        rootViewController?.presentViewController(alertController, animated = true, completion = null)
    }
}

    

Step 4: Use the Alert Presenter in Composables commonMain module 🎨

Now that you have platform-specific implementations, you can call them from your shared Composable code.

Shared Composable Code ✏️


@Composable
fun AlertScreen() {
    val alertPresenter = remember { getAlertPresenter() }
    var showAlert by remember { mutableStateOf(false) }

    Button(
        onClick = {
            showAlert = !showAlert
        }) {
        Text("Show Alert")
    }
    if (showAlert) {
        alertPresenter.ShowAlert(
            title = "Hello!",
            message = "This is a native alert dialog.",
            onDismiss = {
                showAlert = false
                println("Alert dismissed")
            }
        )
    }
}

    

Full Example Project Structure 🗂️

  • Shared Module
    • AlertPresenter.kt 📄
    • getAlertPresenter() 📄
  • Android Module
    • Android-specific implementation in AlertPresenter.android.kt 🤖
  • iOS Module
    • iOS-specific implementation in AlertPresenter.ios.kt 🍎

Output 🖼️

  • 🤖 Android: Displays a native Material Design alert dialog.
  • 🍎 iOS: Displays a native iOS alert using UIAlertController.

Compose Multiplatform Masterclass : Bridging Android & iOS

Learn how seamlessly to bridge Android and iOS with CMP, building shared UIs, platform-specific screens & functionality

Enroll Now

Conclusion 🎉

With Compose Multiplatform, you can keep your shared codebase clean and still provide platform-native experiences where it matters! This approach ensures 🌀 code reusability and 🌟 native user experience.

Happy coding! ☕

Post a Comment

Link copied to clipboard!