Flutter: Dark Theme with Provider

Mais Alheraki
3 min readJan 15, 2020

--

Flutter has great support for dark theming, and in this article, I will explain in brief how easily it can be implemented through your app using Provider.

Giving control to your users is something that will enhance their experience in your app, what I will show you here is how you give them control over the brightness in 3 modes: Light Mode, Dark Mode, and System Mode.

UI Code

We will start with a simple UI that contains 3 RadioButtons, and a sun image as well as a moon image, that will show when the theme is dark.

light mode UI

groupValue with value will determine which RadioButton is selected.

MaterialApp Dark Theme & UI Mode

I will use 2 properties of the MaterialApp widget. The first property is darkTheme, what will happen is that the app will look into which mode the system is using, if it’s dark then it will switch to the darkTheme. How can you control that? there is another property in the MaterialApp, themeMode, which we will be changing to get the desired mode. Obviously, themeMode defaults to ThemeMode.system, that’s why we get the brightness of the system if we gave a value to the darkTheme property.
Guess what we will do? oh right, we will just play around with the value of the themeMode!

Time to Import Provider

provider: ^4.0.1

Provider will help us see the effects of changing the theme immediately, without having to reload the application each time.

We will make a new class, name it ThemeChanger. Then make class and name it ThemeChanger, and paste the following code into it:

Here we simply have a property called _themeMode which will hold whatever theme we choose, to change the value we will use the setter method which will notifyListerners who are listening to this class that the value has changed.

Back to MyApp, here is the final code, with MaterialApp wrapped with a ChangeNotifierProvider:

As you see, I used theme.getTheme in the themeMode, then I will set the themeMode in my RadioButton, using the setter of ThemeChanger class, that will set the mode to the value of that RadioButton

themeChanger.setTheme

That’s it! if you wanna take it a step further you can use shared_preferences to store the value of which theme the user chose, so it stays the same even if the user closed the app.

final result

You can find full code here:

https://github.com/pr-Mais/dark_theme_demo

If you have any questions don’t hesitate to reach me out on twitter: @pr_Mais, or LinkedIn: in/maisalheraki.

Thank you for reading!

--

--

Mais Alheraki

Software engineer, Geek, Designer, Reader & always a Lifetime Learner!