Master declarative UI development for Android, iOS, desktop, and web with Kotlin Multiplatform
What are Composables?
Composables are reusable UI components marked with @Composable
that update automatically when data changes.
@Composable
fun Greeting(name: String) {
Text("Hello, $name!") // Updates when 'name' changes
}
Key Features:
State = Dynamic UI
State changes trigger automatic UI updates through recomposition.
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Button(onClick = { count++ }) {
Text("Count: $count") // Updates on click
}
}
// Stateless reusable component
@Composable
fun CounterDisplay(count: Int, onIncrement: () -> Unit) {
Button(onClick = onIncrement) {
Text("Count: $count")
}
}
// Stateful parent
@Composable
fun CounterApp() {
var count by remember { mutableStateOf(0) }
CounterDisplay(count) { count++ }
}
Why State Hoisting?
✅ Better testability
✅ Component reusability
✅ Clear separation of concerns
Layout | Purpose | Code Example |
---|---|---|
Column | Vertical stacking | Column { Text("A"); Text("B") } |
Row | Horizontal arrangement | Row { Text("Left"); Text("Right") } |
Box | Element overlapping | Box { Image(); Text() } |
LazyColumn | Optimized scrolling list | LazyColumn { items(100) { Item() }} |
Responsive Layout Example
@Composable
fun ProfileCard() {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Image(/*...*/)
Text("User Name", style = MaterialTheme.typography.headlineMedium)
Button(onClick = { /*...*/ }) {
Text("Follow")
}
}
}
What Can Modifiers Do?
Common Modifiers Table
Modifier | Effect | Example Usage |
---|---|---|
.padding(16.dp) | Adds spacing around element | Text(...).padding(16.dp) |
.fillMaxWidth() | Full-width element | Button(...).fillMaxWidth() |
.clickable { } | Adds click interaction | Box(...).clickable { onClick() } |
.background() | Applies color/shape background | Text(...).background(Color.Blue) |
Custom Modifier Example
fun Modifier.cardStyle() = this
.background(Color.White, RoundedCornerShape(8.dp))
.shadow(4.dp)
// Usage
Card(modifier = Modifier.cardStyle()) {
// Content
}
LazyColumn/LazyRow
optimize list performanceInternal Link: Kotlin Multiplatform: A Comprehensive Guide to Cross-Platform Development.
External Link: Dive deeper with the official Kotlin Multiplatform docs.
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