DEV Community

Cover image for Light and dark theme in Flutter with themeMode
Arthur Denner
Arthur Denner

Posted on • Updated on

Light and dark theme in Flutter with themeMode

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...
  }
}
Enter fullscreen mode Exit fullscreen mode
  • 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'),
        );
      },
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Change themeMode with:
ThemeModeHandler.of(context).saveThemeMode(value);
Enter fullscreen mode Exit fullscreen mode
  • Get the current themeMode with:
ThemeModeHandler.of(context).themeMode;
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

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