Dynamic theme in Flutter

Tram Ho

There are many ways to apply dynamic themes in Flutter. Because the Provider is being used by quite a lot of people, let’s try to create applications and set up dynamic themes using Provider.


Create default Flutter counter application: flutter create counter

I have separated MyHomePage and _MyHomePageState into a separate file, lib/home.dart to make it clearer and to avoid the difficulty of tracking.

We then add the provider library to pubspec.yaml


Create a file named themes.dart , which will contain themes and classes related to the theme. First, we will create an enum containing the names of the themes in the class instead of using string to avoid minor errors due to misspellings or error messages if we change the theme name but forgot to change it somewhere in the app. Here I want the app to have 2 themes, light and dark

Once done, we will create a Map containing the properties of the themes included in the app. I want the AppBar, Button in the light theme will be blue, while the dark theme will be green. The brightness attribute will help me automatically change some colors from light to dark to match the theme (for example, in a light theme, the font color is black gray, the background color is white, when the dark theme is used, the font color will be is white, the background is black gray). You can read more about brightness here

Next we will create the AppTheme class that inherits ChangeNotifier , this class will be the class that controls the theme state of our app. You can read more about ChangeNotifier to gain a better understanding of how it works

So that’s it for the main part. Following will be used on Flutter’s default app counter


Open the main.dart file, at main() we will need to wrap the whole App in ChangeNotifierProvider and pass an instance of the AppTheme we just created into the create attribute.

Now the widget will be able to get the other instance using Provider.of<AppTheme>(context) or AppTheme.of(context) So we will use it always in MyApp class because it uses MaterialApp , where we can change the theme. We will change the theme property from the current value via AppTheme.of(context, listen: true).currentTheme

We add the listen: true property because we want to update the view whenever the state of AppTheme changes. So when the state of AppTheme changed, our theme changed as well. We need to change the theme when clicking on a button in the view, so first we need to get the AppTheme instance similar to the one above.

At _MyHomePageState create a variable to contain AppTheme and initialize it in didChangeDependencies

Then I scroll down to the AppBar declaration and add a button to the right of the AppBar to change the theme. At the onPressed function of the button, I call the switchTheme() function of AppTheme to switch between the two themes. I use ?. just in case _theme null

It is done. And here is the result:

Share the news now

Source : Viblo