How to create Toast message in CMP Compose MultiPlatform | Android and iOS
How to create a toast message using Compose Multiplatform (CMP)
In Kotlin Multiplatform (KMP), you typically cannot call platform-specific features like Toast messages directly from the commonMain
module. However, you can achieve this by defining an expect
function or class in commonMain
that acts as an abstraction. Then, implement the corresponding actual
functionality in the androidMain
and iosMain
modules.
Here’s how to set this up step-by-step:
Step 1: Define an Expect Function in Common Code
In your shared commonMain
module, define an expect
function for showing a toast. This acts as a placeholder for the actual implementation on each platform.
commonMain
Create a new class ToastManager
// commonMain/kotlin/ToastManager.kt
expect open class ToastManager() {
fun showToast(message: String)
}
Note: TostManager class gives an error. You need to import classes for Android and iOS. Right click to fix. It will automatically create two classes ToastManager.ios.kt and ToastManager.android.kt.