Light and dark theme in Flutter with themeMode

Arthur Denner
2 min readJul 6, 2020
Flutter Logo in a light and dark background

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!

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 IThemeModeManager interface:
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 ThemeModeHandler widget, wrap MaterialApp with 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 themeMode with:
ThemeModeHandler.of(context).saveThemeMode(value);
  • Get the current themeMode with:
ThemeModeHandler.of(context).themeMode;

Notes

  • The package allows us to set the default themeMode in case we want to force the light or dark theme by default;

Check out an example repo using SharedPreferences 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.

--

--

Arthur Denner

Software Engineer using JavaScript. Learning Flutter, Node, MongoDB and GraphQL. Addicted to TV shows, especially nordic. From 🇧🇷, living in 🇸🇪.