Nucleus
OS integrationTheme

Dark mode detector

Read the operating system's light or dark theme from Kotlin and recompose your Compose UI when it changes.

View as Markdown

darkmode-detector reports whether macOS, Windows or Linux runs in dark mode and tells you when that changes. It comes with nucleus-application; declare dev.nucleusframework:nucleus.darkmode-detector only to use it without nucleusApplication.

darkmode-detectormacOSWindowsLinuxGradle plugin: Not neededWindow runtime: Not needed

Switching System Settings to Light, then through green, pink and orange accents: the app follows each change live

Follow the system theme

Inside nucleusApplication, Compose's isSystemInDarkTheme() recomposes when the user switches the OS theme, so Material, Jewel and third-party libraries follow it too:

fun main() = nucleusApplication {
    val dark = isSystemInDarkTheme()
    MaterialTheme(colorScheme = if (dark) darkColorScheme() else lightColorScheme()) {
        DecoratedWindow(onCloseRequest = ::exitApplication, title = "MyApp") {
            // Content
        }
    }
}

In any other Compose host, call isSystemInDarkMode() from dev.nucleusframework.darkmodedetector. It returns the same value, and falls back to isSystemInDarkTheme() in a @Preview.

How nucleusApplication provides the theme

nucleusApplication feeds the detector's value into Compose's LocalSystemTheme, which every window inherits. It also turns off Compose's once-a-second theme polling (ComposeUiFlags.pollSystemTheme) before it creates any window.

Read the theme outside Compose

val detector = getPlatformDarkModeDetector()
val dark: Boolean = detector.isDark()

val listener = Consumer<Boolean> { isDark -> println("dark mode: $isDark") }
detector.registerListener(listener)
// Later
detector.removeListener(listener)

The listener runs on the thread that receives the OS notification. Move UI work to Dispatchers.Main.

API reference

SymbolNotes
isSystemInDarkMode()Composable, recomposes on change
getPlatformDarkModeDetector()Detector for the current OS, or NoopDarkModeDetector elsewhere
IDarkModeDetector.isDark()Current theme
registerListener(Consumer<Boolean>) / removeListenerChange notifications
NoopDarkModeDetectorAlways light, ignores listeners. For tests and headless runs

What's next

Was this page helpful?
Edit on GitHub

Last updated on