Compose Theme: Animated colors switching from light to dark mode

Barros
2 min readJul 24, 2022
Photo by Azamat E on Unsplash

In this article I’ll explain how to switch from light to dark mode and viceversa, smoothly than usual using animated colors.

Part II: How to change light and dark mode dynamically with SharedFlow

Compose already provides a way to set dark or light palette colors, as shown in the documentation, it’s possible to set the colors in the MaterialTheme .

To get the result it is necessary to create an animateColor function that creates animation for Color type:

Using animateColorAsState, the animation will run automatically on the specific targetValue and the duration, in this case, is two seconds.

Now, we have to animate all the colors of Colors object used by MaterialTheme , with an extension function we create a switch :

Now, we have just to apply the switch to the palette colors:

Calling MyTheme with darkTheme param, we can dynamically update the theme getting a more smoothly result.

The complete implementation:

In the following repository, you can find the completed runnable implementation:

You can find a branch with the implementation of Material 3.

Thank you, I hope you enjoyed reading it.

--

--