Mastering Compose for Cross-Platform App
Compose Multiplatform revolutionizes cross-platform development by letting you build native UIs for Android, iOS, desktop, and web with a single codebase. In this guide, we’ll explore its core concepts—from declarative UI design to state management—so you can create performant, beautiful apps faster than ever.
Step 1: Create a KMP project in Android Studio with the Compose Multiplatform template.
Step 2: Configure build.gradle.kts:
plugins {
id("org.jetbrains.compose") version "1.6.0"
kotlin("multiplatform")
}
kotlin {
androidTarget()
ios()
jvm("desktop")
sourceSets {
val commonMain by getting {
dependencies {
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.material3)
}
}
}
}
@Composable
fun App() {
var count by remember { mutableStateOf(0) }
Column(
modifier = Modifier.fillMaxSize().padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Welcome!", style = MaterialTheme.typography.headlineMedium)
Button(onClick = { count++ }) { Text("Clicked $count times") }
}
}
Platform Entry Points:
setContent { App() } in MainActivity.ComposeViewControllerToSwiftUI.application { Window { App() } }.@Composable
fun Greeting(name: String) {
Text("Hello, $name!") // Updates automatically when 'name' changes
}
Stateful Example (Avoid):
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Button(onClick = { count++ }) { Text("Count: $count") }
}
Stateless Best Practice (State Hoisting):
@Composable
fun CounterApp() {
var count by remember { mutableStateOf(0) }
CounterDisplay(count) { count++ }
}
@Composable
fun CounterDisplay(count: Int, onIncrement: () -> Unit) {
Button(onClick = onIncrement) { Text("Count: $count") }
}
| Layout | Purpose | Example |
|---|---|---|
| Column | Vertical stacking | Column { Text("A"); Text("B") } |
| Row | Horizontal alignment | Row { Text("Left"); Text("Right") } |
| Box | Overlapping elements | Box { Image(); Text() } |
| LazyColumn | Optimized lists | LazyColumn { items(100) { ... } } |
Text(
"Styled Text",
modifier = Modifier
.padding(16.dp)
.background(Color.Blue, RoundedCornerShape(8.dp))
.clickable { /* Handle click */ }
)
Common Modifiers:
.padding(), .size(), .background().fillMaxWidth(), .weight() (for responsive layouts)Introduction: Transform Your Cross-Platform Development with Material Design 3 Are you ready to revolutionize your… Read More
Jetpack Compose 1.8 rolls out handy features like Autofill integration, slick Text enhancements including auto-sizing… Read More
Reified Keyword in Kotlin: Simplify Your Generic Functions Kotlin's reified keyword lets your generic functions know the… Read More
Android Studio Cloud: Ditch the Setup, Code Anywhere (Seriously!) Alright, fellow Android devs, gather 'round… Read More