How to Add Dark Theme in Compose Multiplatform with Material3 (iOS, Android)
2 min readMay 6, 2024
Step 1. Create Project KMP
Visit this Link for make Kotlin MultiPlatfrom project, you can setup like this, after that you can export project and open with Android Studio
Step 2. Create Custom Color with M3 (Material 3)
You can customize the color as desired, visit the m3 website Link, on this website can also be seen the appearance of Light theme and Dark theme, after finish you can export the color
Step 3. Insert resource to Project
Add resource to project Compose Multiplatform composeApp → src → commonMain → kotlin[commonMain] → ui → theme. Create class Color.kt and Theme.kt
Color.kt
val md_theme_light_primary = Color(0xFF006B58)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
...
val md_theme_dark_primary = Color(0xFF5DDBBC)
val md_theme_dark_onPrimary = Color(0xFF00382D)
val md_theme_dark_primaryContainer = Color(0xFF005142)
....
val seed = Color(0xFF006B58)
val freshColor = Color(0xFF44FF78)
val staleColor = Color(0xFFFF9E44)
val primaryColor
@Composable
get() = if (isSystemInDarkTheme()) Color(0xFF86A8FC)
else Color(0xFF283556)
val headerColor
@Composable
get() = if (isSystemInDarkTheme()) Color(0xFF0C0C0C)
else Color(0xFF283556)
val surfaceColor
@Composable
get() = if (isSystemInDarkTheme()) Color(0xFF161616)
else Color(0xFFFFFFFF)
val textColor
@Composable
get() = if (isSystemInDarkTheme()) Color(0xFFFFFFFF)
else Color(0xFF000000)
Theme.kt
val LightColors = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
...
)
val DarkColors = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
...
)
Done, you just have to use it. For example as below
Text(
modifier = Modifier.fillMaxWidth(),
text = if (isSystemInDarkTheme()) "Dark Theme" else "Light Theme",
fontSize = 60.sp,
color = textColor,
textAlign = TextAlign.Center
)