Jetpack Compose Material 3 — Complete Guide
In this tutorial, you'll learn about Jetpack Compose Material 3. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your Material 2 components look wrong after Migration, Button has weird border radius, or TextField lost its label styling.
Wrong Approach ❌
// Mixing M2 and M3 — inconsistent styling
@Composable
fun BadM3() {
MaterialTheme { // M2 theme
Button(onClick = {}) { Text("Click") } // M3 button with M2 theme
}
}
// Ignoring M3 component parameter changes
@Composable
fun OldButton() {
Button(
onClick = {},
backgroundColor = Color.Red // M2 API — doesn't exist in M3!
) { Text("Click") }
}
Output: Compilation error or mismatched styling.
Right Approach ✅
@Composable
fun GoodM3() {
// M3 theme with dynamic color support
val context = LocalContext.current
val colorScheme = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
dynamicLightColorScheme(context)
} else {
lightColorScheme(primary = Purple40)
}
MaterialTheme(colorScheme = colorScheme) {
// M3 Button
Button(
onClick = {},
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary
)
) { Text("Click") }
// M3 TextField with updated API
var text by remember { mutableStateOf("") }
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") },
supportingText = { Text("Helper text") }
)
// M3 Card
Card(colors = CardDefaults.cardColors()) {
Text("Card content")
}
}
}
Output: Consistent Material 3 styling with dynamic colors.
Prevention
- Use only Material 3 dependencies (
material3, notmaterial). - Check M3 API changes —
backgroundColorbecamecontainerColor. - Use
MaterialTheme.colorSchemefor all colors. - Enable dynamic colors on Android 12+.
Common Mistakes with compose material3
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro