Material 3 theming
Why it matters
- Every screen in a real app reads colors, type, and shapes from the theme. Hardcoding any of them breaks dark mode or dynamic color and creates visual bugs that are hard to track down.
- Interviewers ask how theming propagates through the composition tree without passing colors as parameters. Knowing CompositionLocal answers that directly.
- Dynamic color (Material You) is available on Android 12+, but an app only gets it if its theme opts in. Supporting it, with a fallback scheme for older devices, is now the default in the Android Studio Compose templates.
- A single theme function at the app root replaces dozens of per-screen color constants. This is the mechanism that makes a large app stay visually consistent with one change.
The simple explanation
- Think of MaterialTheme as a uniform policy for a building.
- The policy says: walls are this color, doors have this radius, signs use this font.
- Every room (composable) reads the policy from a shared board (CompositionLocal) instead of painting itself independently.
- When the building switches to night mode, the board updates once; every room repaints automatically.
- Dynamic color is like letting the building's exterior (wallpaper) influence the interior palette.
- If one room ignores the board and paints itself a fixed blue, it looks wrong at night.
Material3 exposes three theme objects: ColorScheme, Typography, and Shapes. You pass them into the MaterialTheme composable at the root of your composition. Internally, MaterialTheme wraps its children in CompositionLocalProvider, setting the (internal) LocalColorScheme, LocalTypography, and LocalShapes.
Any composable below the MaterialTheme call reads values through MaterialTheme.colorScheme, MaterialTheme.typography, or MaterialTheme.shapes. These are CompositionLocal reads, so nobody has to pass colors down as parameters. When the theme changes (for example light to dark), composables that read the theme recompose with the new values. Theme changes are rare, so this costs little.
| Object | Key properties | Typical use |
|---|---|---|
ColorScheme | primary, onPrimary, surface, onSurface, surfaceVariant, error, outline | backgrounds, text, borders |
Typography | displayLarge, headlineMedium, titleLarge, bodyLarge, labelMedium | text styles on Text |
Shapes | extraSmall, small, medium, large, extraLarge | corner radius on Card, FAB, dialogs, sheets |
Dynamic color (Android 12+, API 31) derives a ColorScheme from the user's wallpaper. You call dynamicLightColorScheme(context) or dynamicDarkColorScheme(context). On older devices you fall back to lightColorScheme() / darkColorScheme(). The check uses Build.VERSION.SDK_INT >= Build.VERSION_CODES.S.
isSystemInDarkTheme() (from androidx.compose.foundation) reads the system dark-mode flag. You pass its result into your theme function so the correct scheme is selected before any child composable runs.
A common mistake is wrapping a screen in a second theme call that sets its own scheme, such as MaterialTheme(colorScheme = lightColorScheme()). That creates a nested theme scope that shadows the app theme for that subtree, so the screen stays light in dark mode. Keep your app theme at the root, and nest a theme only when you deliberately want to override a subtree.
Notes
MaterialThemeis a composable that sets threeCompositionLocalvalues:LocalColorScheme,LocalTypography,LocalShapes. Children read them viaMaterialTheme.colorScheme,.typography,.shapes.MaterialThemeparameters default to the current theme values, so a nestedMaterialTheme(shapes = ...)changes only shapes and inherits the rest from the outer theme.- Dynamic color APIs (
dynamicLightColorScheme,dynamicDarkColorScheme) require API 31 (Android 12). Always provide alightColorScheme()/darkColorScheme()fallback for older devices. isSystemInDarkTheme()lives inandroidx.compose.foundation. It reads the system dark-mode preference and returns aBoolean.- Customise
TypographyorShapeswith named arguments (Typography(titleLarge = ...)) or.copy(). Every role you do not pass keeps its Material 3 default. - Place your app theme at the
setContentroot. A nestedMaterialThemethat passes its owncolorSchemeshadows the outer one for that subtree, which is a bug unless you meant it. ColorSchemeroles follow a pattern:primary/onPrimary,surface/onSurface,surfaceVariant/onSurfaceVariant,error/onError. Theon*role is the text/icon color that contrasts with its base.Shapeshas five slots:extraSmall(4dp),small(8dp),medium(12dp),large(16dp),extraLarge(28dp) by default.Cardusesmedium,FloatingActionButtonuseslarge,AlertDialogusesextraLarge. Buttons use a fully rounded shape that is not one of the five slots.- In Material3 the accessor is
MaterialTheme.colorScheme, notMaterialTheme.colors(that was Material2). If the Material2 library is also on the classpath and you import itsMaterialThemeby mistake, the code compiles but reads Material2 default colors, not your theme. - Dynamic color reads system color resources that are derived from the wallpaper. When the user changes wallpaper colors, the system updates those resources and normally recreates running activities, so the theme picks up the new scheme without extra code.
Code example
This shows a single AppTheme function that selects light, dark, or dynamic color, customises two shape slots, and a GreetingCard that reads every value from the theme instead of hardcoding anything.
// Theme.kt – one theme function, called once in setContent
@Composable
fun AppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
dynamicColor: Boolean = true,
content: @Composable () -> Unit,
) {
// Pick the right ColorScheme; fall back for pre-Android 12
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ->
if (darkTheme) dynamicDarkColorScheme(LocalContext.current)
else dynamicLightColorScheme(LocalContext.current)
darkTheme -> darkColorScheme()
else -> lightColorScheme()
}
// Override only the slots you need; the rest keep Material3 defaults
val shapes = Shapes(
medium = RoundedCornerShape(16.dp),
large = RoundedCornerShape(24.dp),
)
MaterialTheme(
colorScheme = colorScheme,
typography = Typography(), // default M3 type scale
shapes = shapes,
content = content,
)
}
// A screen composable that reads everything from the theme
@Composable
fun GreetingCard(name: String) {
Card(
shape = MaterialTheme.shapes.medium,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
),
) {
Text(
text = "Hello, " + name,
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(16.dp),
)
}
}- The
whenblock guarantees aColorSchemefor every API level; the dynamic branch is guarded byBuild.VERSION.SDK_INT >= Build.VERSION_CODES.S. Shapes(medium = ..., large = ...)uses named parameters so the other three slots (extraSmall,small,extraLarge) keep their Material3 defaults.GreetingCardnever references a rawColororDpvalue; it readsMaterialTheme.colorScheme.surfaceVariantandMaterialTheme.shapes.medium, so it adapts to light, dark, and dynamic modes automatically.
Run the idea in plain Kotlin
fun main() {
// Simulating theme logic without Android dependencies
val isDark = true
val useDynamic = true
val sdkInt = 31 // Android 12
val scheme = when {
useDynamic && sdkInt >= 31 -> "Dynamic"
isDark -> "Dark"
else -> "Light"
}
val result = "Selected scheme: " + scheme
println(result)
}Expected output: Selected scheme: Dynamic. Change sdkInt to 30 and it prints Selected scheme: Dark.
In production
- Users reported that two onboarding screens showed white text on a white background after switching to dark mode.
- The rest of the app adapted correctly, so the bug was not in the theme function itself.
- The two screens used
Color.WhiteandColor(0xFF1A1A1A)literals instead ofcolorScheme.onSurfaceandcolorScheme.surface.
- The team grepped the codebase for
Color.literals outside the theme file and found several occurrences across multiple screens. - Each literal was replaced with the matching
MaterialTheme.colorSchemerole (e.g.onSurface,surfaceVariant). - A lint check was added to the CI pipeline that flags any
Color(orColor.White/Color.Blackusage outsideTheme.kt. - After the fix, dark-mode screenshots in the visual-regression suite matched the light-mode layout with correct contrast.
- Users on Pixel 6 (Android 12) saw the default purple Material3 baseline palette instead of the wallpaper-derived colors.
- The theme function called
lightColorScheme()unconditionally; the dynamic branch was behind a feature flag that was never enabled in production. - No crash or log appeared, so the issue was only visible in user screenshots.
- The team reproduced the issue on a Pixel 6 emulator with a colorful wallpaper and confirmed the app used the static baseline scheme.
- The feature flag was removed; the
whenblock now checksBuild.VERSION.SDK_INT >= Build.VERSION_CODES.Sand callsdynamicLightColorScheme/dynamicDarkColorScheme. - A screenshot test on an API 31+ emulator with a non-default wallpaper was added, so a missing dynamic branch shows up as a diff.
- The fix shipped in the next release; user screenshots in the feedback channel showed the new wallpaper-tinted palette.
Common mistakes
- Hardcoding Color(0xFF6200EE) or Color.White in a screen composable. The color does not change with dark mode or dynamic color, so the UI looks broken in one mode. Always read from
MaterialTheme.colorSchemeroles. - Wrapping a screen in a theme call with a fixed scheme. A nested
MaterialTheme(colorScheme = lightColorScheme())creates a secondCompositionLocalscope that shadows the app theme. Children of the inner theme ignore dark mode and dynamic color. Keep the app theme at the root. - Omitting the Build.VERSION.SDK_INT guard before calling dynamicLightColorScheme. The dynamic APIs are not available on pre-Android 12 devices. Without the guard, the app crashes on API 30 and below.
- Overriding a type role with a bare
TextStyle(fontSize = 30.sp). The new style loses the default line height, letter spacing and weight of that role. Start from the default style instead:Typography().headlineMedium.copy(fontSize = 30.sp). - Using MaterialTheme.colors (Material2 accessor) in a Material3 project.
MaterialTheme.colorsdoes not exist inandroidx.compose.material3. If Material2 is also a dependency, the wrong import compiles and silently returns Material2 default colors. Useandroidx.compose.material3.MaterialTheme.colorScheme. - Painting a background with
Modifier.background(colorScheme.surface)instead of usingSurface.Surfacealso setsLocalContentColorto the matchingon*color, soTextandIconinside get the right contrast. A plain background does not, and text can end up with the wrong color in dark mode.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How does MaterialTheme make its values available to child composables?”
“What is dynamic color and how do you implement it correctly?”
“A screen shows white text on a white background in dark mode. How do you debug it?”
“How do you customise typography or shapes without breaking the rest of the Material3 defaults?”
Quiz
What mechanism does MaterialTheme use to make colorScheme, typography, and shapes available to child composables?
On which minimum Android version are dynamicLightColorScheme and dynamicDarkColorScheme available?
Text inside a Box with Modifier.background(MaterialTheme.colorScheme.surface) has the wrong color in dark mode. What is the best fix?
What is the correct way to override one typography style in Material3?
0 of 4 answered
Mini task
Add dynamic color to your app's theme (15 min)
-
Open your existing theme file (or create
Theme.kt). Write anAppThemecomposable that takesdarkTheme: Boolean = isSystemInDarkTheme()anddynamicColor: Boolean = true. -
Inside
AppTheme, build awhenblock that returnsdynamicDarkColorScheme(LocalContext.current)ordynamicLightColorScheme(LocalContext.current)whendynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S, and falls back todarkColorScheme()/lightColorScheme()otherwise. -
Pass the selected
colorSchemeintoMaterialTheme. Also passTypography()and aShapesobject that overridesmediumtoRoundedCornerShape(16.dp). -
In your
MainActivity.setContent, replace any existing theme call withAppTheme { /* your root composable */ }. -
Add a
Cardwithshape = MaterialTheme.shapes.mediumandcontainerColor = MaterialTheme.colorScheme.surfaceVariantinside the root composable. Put aTextwithstyle = MaterialTheme.typography.titleLargeandcolor = MaterialTheme.colorScheme.onSurfaceVariantinside the card. -
Run the app in light mode, dark mode, and (on an Android 12+ device or emulator) with a colorful wallpaper. Confirm the card background and text color change with each mode.
Done when: the card adapts its colors in all three modes, no Color.White or Color(0xFF...) literals appear in the screen composable, and the app does not crash on an API 30 emulator.