The plugin provides powerful tools to detect the current theme (light or dark) and respond to theme changes in real-time. This feature is available on Android 9 (API level 28) and higher.
Use the DynamicColor.dayNight() method to check whether the device is currently using light or dark theme:
DynamicColor.dayNight(function(theme) { if (theme == 'light') { // Light theme is active console.log('User is using light theme'); } else { // theme == 'dark' // Dark theme is active console.log('User is using dark theme'); }});
The dayNight() method works on Android 9+ for theme detection, while Dynamic Colors require Android 12+.
The plugin fires a dynamicColorChange event whenever the theme changes or when the dynamic colors change (for example, when the user changes their wallpaper).
document.addEventListener('dynamicColorChange', function(event) { event.changed = { dayNight: true, // true if the DayNight theme have changed (dark theme turned on or off) dynamicColor: true, // true if the DynamicColor colors/palette have changed } if (event.changed.dayNight) { DynamicColor.dayNight(function(theme) { if (theme == 'light') { console.log('Switched to light theme'); } else { // theme == 'dark' console.log('Switched to dark theme'); } }); } if (event.changed.dynamicColor) { // Refresh dynamic colors getDynamicColor(); }});
Both properties can be true simultaneously if the user changes their wallpaper and theme at the same time.
Only refresh what’s necessary based on what changed:
document.addEventListener('dynamicColorChange', function(event) { // Only update theme-specific elements if theme changed if (event.changed.dayNight) { updateThemeSpecificElements(); } // Only refresh colors if dynamic colors changed if (event.changed.dynamicColor) { updateDynamicColors(); }});
DynamicColor.isDynamicColorAvailable(function(available) { if (available) { // Use dynamic colors getDynamicColor(); document.addEventListener('dynamicColorChange', getDynamicColor); } else { // Fall back to static colors useStaticColorScheme(); }});
You can create smooth transitions when the theme changes:
:root { /* Add transitions to color changes */ transition: background-color 0.3s ease, color 0.3s ease;}body { background-color: var(--md-sys-color-background); color: var(--md-sys-color-on-background);}
document.addEventListener('dynamicColorChange', function(event) { if (event.changed.dayNight) { // Add a class to trigger CSS animations document.body.classList.add('theme-changing'); // Update colors getDynamicColor(); // Remove class after animation setTimeout(() => { document.body.classList.remove('theme-changing'); }, 300); }});
The dynamicColorChange event is only fired when your app is in the foreground. If the user changes their theme while your app is in the background, the event will fire when they return to your app.