Easy approach to multiple themes in flutter application

One of the trending concepts in the mobile application is the ability to have multiple themes such as light and dark themes, and you can have as many themes as possible in your application. the question right now is how to manage the theme in order to cut across all pages. thinking about managing the state of your theme in the application. one of the ways of managing the state is using stateful widget which is a terrible approach and it’s inefficient and the other approach is to use statement package, there are a lot of statement management packages in flutter such as Providers, BLOC, Redux, Mobx e.t.c in this article I will be chosen provider state management package.
Provider State management package
using a state management package allows you to manage your state globally in your application, it is more like having a global store where each page, widgets can connect directly to and access and manipulate data.
1. How to install Provider Package
add below snippet in your pubspec.yml file under the dependencies section
provider: ^3.1.0+1
create a dart file that has all your theme definition
Create a theme model
you need to create your theme model
Explanation:
1.we are creating an enum type for our theme, which we allow us to assign a type to each Themedata, it also helps us to check currently theme efficiently
-
We create a class that extends ChangeNotifier, create currentTheme as a property of ThemeData and set the default value to darkTheme and also property _themeType then assign your current themeType to it. you can set to any theme of your choice, it’s the theme that will comes with the app at the default.
-
create a method that handles the toggling of your theme from theme 1 to theme 2. But the most important part is to call notifyListener() method, it is the method that informs your store that your state value has change.
Wrap provider Class as a parent of your MaterialApp, which will allow all pages, widgets e.t.c have access to the provider value.
Consuming your state value anywhere in your application
Provider.of<object>(context);
it allows you to access your provider store value and access your data. by specifying the ThemeModel.
below is your output
Finally, Adding toggle widget to your app, this is the widget that will enable you to switch from theme 1 to theme 2 and vice-versa. for the sake of simplicity of the article, I will just add a RaisedButton widget to MyHomePage Screen.
snippet below
NB:Provider.of<ThemeModel>(context).toggleTheme(); allows you to connect to your themeModel class and run toggleTheme() method.
Conclusion
The main purpose of this article is to allow you, to have an understanding of how you can create multiple themes based flutter application using Provider State management plugin.
