Last active
May 4, 2024 04:53
-
-
Save Kounex/ccac4c4dff07d69deb6fcacbdeebaa3c to your computer and use it in GitHub Desktop.
Flutter Theming: InheritedWidget with ValueNotifier
This file contains 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
import 'package:flutter/material.dart'; | |
void main() { | |
runApp( | |
SettingsStore( | |
child: App(), | |
), | |
); | |
} | |
class SettingsStore extends InheritedWidget { | |
final ValueNotifier<ThemeData> theme = ValueNotifier(ThemeData.light()); | |
SettingsStore({@required Widget child}) : super(child: child); | |
static SettingsStore of(BuildContext context) => | |
context.dependOnInheritedWidgetOfExactType<SettingsStore>(); | |
void updateTheme(ThemeData theme) => this.theme.value = theme; | |
@override | |
bool updateShouldNotify(SettingsStore oldWidget) => oldWidget.theme != this.theme; | |
} | |
class App extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return ValueListenableBuilder( | |
valueListenable: SettingsStore.of(context).theme, | |
builder: (context, theme, child) => MaterialApp( | |
theme: theme, | |
home: SettingsView(), | |
), | |
); | |
} | |
} | |
class SettingsView extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('Settings'), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
RaisedButton( | |
onPressed: () => | |
SettingsStore.of(context).updateTheme(ThemeData.light()), | |
child: Text('Light'), | |
), | |
RaisedButton( | |
onPressed: () => | |
SettingsStore.of(context).updateTheme(ThemeData.dark()), | |
child: Text('Dark'), | |
), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment