Created
March 21, 2022 22:58
-
-
Save theLee3/760ea404aea307cb4daf4f8aa692fc40 to your computer and use it in GitHub Desktop.
An approximation of Flutter's [Theme] implementation, demonstrating simple [InheritedWidget] use.
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
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