Arthur Denner

Light and dark theme in Flutter with themeMode

Light and dark theme in Flutter with themeMode

Subscribe to my newsletter and never miss my upcoming articles

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

#showhashnode#flutter#design#tutorial
 
Share this