Flutter – Dark Theme
Nowadays almost all the mobile application uses a dark theme, for example, Instagram, Whatsapp, Youtube, etc. It’s easy to implement in Flutter, Just a few lines of code require to achieve this. But before doing that let’s explore some important concept in flutter which are used to achieve the dark theme
ThemeData Class :
ThemeData class defines the theme for App. It’s used inside MaterialApp, It helps to configure the appearance of the entire app. We can override it as per our requirement and make changes.
Now let’s dig into the code and explore the new things in the ThemeData class.
Important parameters in ThemeData class:
1. Brightness :
Describes the contrast of a theme or color palette.
2. visualDensity :
Visual density is the vertical and horizontal “compactness” of the components in the UI. Note: horizontal and vertical density must be less than or equal to max Horizontal or MaximumVeriticalDensity i.e. 4.0
3. primaryColor :
Defines the primary color for the app, similarly, we can define the primary color for a light theme and a dark theme.
Similarly, we can define the accentColor, accentColorLight, accentColorDark, feel free to use them in your app.
Defines the color, opacity, and size of icons.
Similarly, you can have other properties in flutter official docs. I personally recommend visiting at least once in Flutter official docs.
Now we get enough knowledge to accomplish our goal, let’s get started. We are going to use the Provider package, this is not mandatory we can do the dark theme implementation without Provider But for better architecture, we are using it. Add provider package into pubspec.yaml file.
This is our main class the execution starts from this class. Just take a look at the theme properties of the MaterialApp(), all the things we have discussed above are written here, I guess you get some clarity here.
DarkThemeExample Class :
This class contains our UI part of the app, when we tap on the bulb image it will call the clickEvent() which is defined in our business class. Here we just toggle one boolean variable to get a dark theme and light theme.
ButtonTapListener Class :
This class is the business class that is we do all the business logic or operation here. For our example, the functionality of this class is less, But this is the right approach to separate our UI and business logic & follow good architecture to build an app.
In this class, we extend the ChangeNotifier class which is in the provider package. Just notice the clickEvent() , there we are using notifyListner(). When we call this function we just tell the listeners to rebuild it to get updated value or new value. In our case, we just toggle the boolean value. By looking at it, you can think in this way this is a mess, why we do all these things for this small app. But believe me, we need to follow at least one architecture pattern. If you do not want to use it feel free to use a simple approach.