Light and dark theme in Flutter with themeMode

Software Engineer using JavaScript. Learning Flutter, Node, MongoDB and GraphQL. Addicted to TV shows, especially nordic. From π§π·, living in πΈπͺ.
Flutter has built-in support to light and dark themes.
The MaterialApp widget has a property called themeMode. If we specify the darkTheme and theme properties, we can use themeMode to control it. The property defaults to ThemeMode.system, which will use the correct theme based on the device's settings.
But what if we want to enable the user to change it and persist their change? We can use theme_mode_handler!
{% github arthurdenner/theme_mode_handler no-readme %}
With this package, we can accomplish the task and have total control on where to persist the user's choice: SharedPreferences, Hive, Firebase... anywhere.
Usage
- Create a class that implements the
IThemeModeManagerinterface:
class MyManager implements IThemeModeManager {
@override
Future<String> loadThemeMode() async {
// Load from wherever you want...
}
@override
Future<bool> saveThemeMode(String value) async {
// Save wherever you want...
}
}
- Import the
ThemeModeHandlerwidget, wrapMaterialAppwith it and pass an instance of the manager to it:
import 'package:theme_mode_handler/theme_mode_handler.dart';
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ThemeModeHandler(
manager: MyManager(),
builder: (ThemeMode themeMode) {
return MaterialApp(
themeMode: themeMode,
darkTheme: ThemeData(
brightness: Brightness.dark,
// other properties...
),
theme: ThemeData(
brightness: Brightness.light,
// other properties...
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
},
);
}
}
- Change
themeModewith:
ThemeModeHandler.of(context).saveThemeMode(value);
- Get the current
themeModewith:
ThemeModeHandler.of(context).themeMode;
Notes
- The package allows us to set the default
themeModein case we want to force the light or dark theme by default;
Check out an example repo here.
If you're using a different solution or have any suggestions to improve this example, feel free to share it in the comments.
I hope you enjoyed this post and follow me on any platform for more.




