Maya Mohite
Globant
Published in
2 min readApr 27, 2020

--

Flutter Dynamic Theme: Dark Mode & Custom Themes

Dynamic Themes

Nowadays, all devices and applications come with the Dark mode.

Why Dark mode?
Dark
mode settings help devices with OLED (Organic light emitting diodes)and AMOLED (Active Matrix Organic light emitting diodes)screens by consuming less power and saving on battery. Each pixel on your OLED display is lit up individually. So, when your display background is white, all the pixels light up, consuming more power.

So, let's bring this power in Flutter,
We use the provider pattern to notify UI whenever application theme changes.
Add provider dependency in pubspec.yaml

Create a theme provider like below

Create a custom light theme and dark theme

Add Theme provider in main.dart.
In MyApp class, assign your custom Dark and Light theme to ‘darkTheme’ and ‘theme’ attributes. Set ‘themeMode’ value as ‘themeNotifier.getThemeMode()’. So whenever we modify a theme in ‘ThemeProvider’ it will update ‘themeMode’ and app theme will be modified.

If we are using SharedPreferences to get the stored theme then above code will modify like:

HomePage having option to navigate to the Settings screen to modify a theme.

In Settings Screen, we have given three options to change the theme to ‘System’, ‘Dark’ or ‘Light’. On click of any option, we save selected Theme in Shared Preferences and update the ThemeNotifier which notify to application about Theme changes.

When the theme changes from Light to dark or dark to Light all the icons, text, app bar theme will change automatically as per custom theme declared in AppTheme class. If you want to give custom color to text or any widget then add code like below

var isDarkTheme = Theme.of(context).brightness == Brightness.dark;
Text("APP",color : isDarkTheme ? AppColors.darkPink : AppColors.textBlack,)

You can check the source code from here.

I hope you like the Article.

The day-night background animation is created in Rive/Flare.

Watch the tutorial here.

--

--