DEV Community

loading...
Cover image for Light and dark theme in Flutter with themeMode

Light and dark theme in Flutter with themeMode

arthurdenner profile image Arthur Denner ・Updated on ・2 min read

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 logo arthurdenner / theme_mode_handler

Flutter widget to change `themeMode` during runtime and persist it across restarts.

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 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.

Discussion (1)

pic
Editor guide
Collapse
bvdwalt profile image
Bennie van der Walt

Hi Arthur,

Great package, just came across this and I'm already busy implementing it in my app as I type this.

Github Repo