In the field of application development, switching themes is one of the trending features. Changing the theme can reduce the user’s eye strain and also the battery life.
Here, we are going to learn how to develop an application that can change the themes dynamically.
Get full code: Github
Live working example :
In this project, we are going to use two packages Provider and SharedPreferences.
- Provider: It is one of the famous packages that is used for dependency injection and state management.
- SharedPreferences: Shared Preferences allow us to store the minimal amount of primitive data as key/value pairs in a file on the device. Here we use it to store the current theme so that the user gets the same after closing and returning back to the application.
We can achieve this in two ways: one by adding a custom option and the other by automatically switching the theme based on the system settings.
In Flutter, we can change the theme throughout the app with the help of ThemeData in MaterialApp constructor. The default theme will be shared throughout the app when no theme is provided.
MaterialApp(
theme: ThemeData( ... ), // to declare the theme to throughout the application
);
ThemeData is used to configure the appearance of the entire app. It consists of a large number of properties to declare the theme in our app.
ThemeData.dark() is responsible to provide the dart theme across the application.
MaterialApp(
theme: ThemeData.dark(), // default dark the theme
);

ThemeData.light() gives the Light blue theme, which is a default theme for every flutter application.

We can also change the primaryColor of the theme. We can obtain as follows:
MaterialApp(
theme: ThemeData(
brightness: Brightness.light,
primaryColor: Colors.green,
primarySwatch: Colors.green
),);

0 comments:
Post a Comment