Flutter: Add Dark/Light mode to your app
In this article, I will be sharing how you can add Dark/Light mode feature to your Flutter app using Provider & Shared Preferences.
So now lets begin. First of all, lets add the provider and shared_preferences to pubspec.yaml file.
Make a new file dark_mode.dart file and define light and dark theme according to the need as shown below.
Now add a class ThemeNotifier in dark_mode.dart file which contains all handling and loading of preferences the app will persist for futher use i.e it will save the user choice of theme and load the app in that particular theme even after closing and reopening the app.
And at last in the main.dart file, wrap the MaterialApp widget with the ChangeNotifierProvider. The MaterialApp returns a StatelessWidget called HomePage() in which we have a added a SwitchListTile widget on which toggling changes the theme of our app. The code is shown below.
All done! Now run your app and check it. Thats it.