Skip to content

Instantly share code, notes, and snippets.

@theLee3
Created March 21, 2022 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theLee3/760ea404aea307cb4daf4f8aa692fc40 to your computer and use it in GitHub Desktop.
Save theLee3/760ea404aea307cb4daf4f8aa692fc40 to your computer and use it in GitHub Desktop.
An approximation of Flutter's [Theme] implementation, demonstrating simple [InheritedWidget] use.
class MyThemeProvider extends StatefulWidget {
const MyThemeProvider({Key? key, required this.child}) : super(key: key);
final Widget child;
@override
State<MyThemeProvider> createState() => _MyThemeProviderState();
}
class _MyThemeProviderState extends State<MyThemeProvider> {
var data = const MyThemeData();
@override
Widget build(BuildContext context) {
return MyTheme(
data: data,
child: widget.child,
);
}
}
class MyTheme extends InheritedWidget {
const MyTheme({
Key? key,
required this.data,
required Widget child,
}) : super(key: key, child: child);
final MyThemeData data;
@override
bool updateShouldNotify(covariant MyTheme oldWidget) => false;
static MyThemeData of(BuildContext context) {
final result = context.dependOnInheritedWidgetOfExactType<MyTheme>();
assert(result != null, 'No MyTheme in current BuildContext.');
return result!.data;
}
}
@immutable
class MyThemeData {
const MyThemeData({
this.backgroundColor = Colors.white,
this.primaryColor = Colors.blue,
this.textColor = Colors.black87,
});
final Color backgroundColor;
final Color primaryColor;
final Color textColor;
MyThemeData copyWith({
Color? backgroundColor,
Color? primaryColor,
Color? textColor,
}) {
return MyThemeData(
backgroundColor: backgroundColor ?? this.backgroundColor,
primaryColor: primaryColor ?? this.primaryColor,
textColor: textColor ?? this.textColor,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment