Created
May 1, 2024 19:13
-
-
Save SaltySpaghetti/f4aac7697dcef0e18c3816bb16ac5b16 to your computer and use it in GitHub Desktop.
Easy Theme Manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class EasyTheme extends InheritedWidget { | |
| final ValueNotifier<ThemeMode> theme = ValueNotifier(ThemeMode.system); | |
| EasyTheme({required super.child, super.key}); | |
| static EasyTheme? maybeOf(BuildContext context) => | |
| context.dependOnInheritedWidgetOfExactType<EasyTheme>(); | |
| static EasyTheme of(BuildContext context) { | |
| final EasyTheme? result = maybeOf(context); | |
| assert(result != null, 'No EasyThemeManager found in context'); | |
| return result!; | |
| } | |
| void toggleTheme() { | |
| final isLightTheme = theme.value == ThemeMode.light; | |
| theme.value = isLightTheme ? ThemeMode.dark : ThemeMode.light; | |
| } | |
| @override | |
| bool updateShouldNotify(covariant EasyTheme oldWidget) => | |
| oldWidget.theme.value != theme.value; | |
| } | |
| class EasyThemeBuilder extends StatelessWidget { | |
| final Widget Function(BuildContext context, ThemeMode themeMode) builder; | |
| const EasyThemeBuilder({ | |
| required this.builder, | |
| super.key, | |
| }); | |
| @override | |
| Widget build(BuildContext context) { | |
| return EasyTheme( | |
| child: Builder(builder: (context) { | |
| return ValueListenableBuilder( | |
| valueListenable: EasyTheme.of(context).theme, | |
| builder: (context, value, _) { | |
| return builder.call(context, value); | |
| }, | |
| ); | |
| }), | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment