Skip to content

Instantly share code, notes, and snippets.

@AyushBherwani1998
Last active May 5, 2023 17:35
Show Gist options
  • Select an option

  • Save AyushBherwani1998/31cb6ca2db6a98618d3060439d294c15 to your computer and use it in GitHub Desktop.

Select an option

Save AyushBherwani1998/31cb6ca2db6a98618d3060439d294c15 to your computer and use it in GitHub Desktop.
A sample to demostrate setting up a custom theme for the app
/// Code for setting up customTheme
class CustomThemeData extends Diagnosticable {
final Color varibaleName;
/// Other things can also come, apart from Color, like whole BoxDecoration,
/// padding, text styles etc for widgets. If you keep text style, you can
/// have custom styling for text defined at single place, and you can use like
/// CustomTheme.of(context).customTextStyle.
/// Similar to what we use Theme.of(context).textTheme.body
const CustomThemeData({
required this.varibaleName,
})
/// This will help you to modiy only few propreties and keep rest it is,
/// often times we use Theme.of(context).copyWith()
CustomThemeData.copyWith({
Color? varibaleName
/// Other parameters
}) {
return CustomThemeData(varibaleName: varibaleName ?? this.varibaleName);
}
@override
int get hashCode {
return Object.hash(
varibaleName,
/// Other params
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
if (other is! CustomThemeData) {
return false;
}
final CustomThemeData customThemeData = other;
/// This is important for theme to change properly
return customThemeData.varibaleName == varibaleName && customThemeData.otherParams == otherParams;
}
}
class CustomTheme extends InheritedWidget {
const CustomTheme({
Key? key,
required this.data,
required Widget child,
}) : super(key: key, child: child);
final CustomThemeData data;
static CustomThemeData of(BuildContext context) {
final CustomTheme? customTheme =
context.dependOnInheritedWidgetOfExactType<CustomTheme>();
return customTheme!.data;
}
@override
bool updateShouldNotify(CustomTheme oldWidget) {
return true;
}
}
/// Setup CustomThemeData in the main after setting up the varibale which holds Dark and light mode configuration
/// You can have a singleton, whatever you prefer to initialize and hold the object
/// You can use your choice of state managemnet, whatever you prefer to hold state.
final isDarkMode = Provider.of<AppConfiguration>(context);
final customThemeData = CustomThemeData(
vairbaleName: isDarkMode ? darkColor : lightColor,
/// Other parameters
)
/// Initialize CustomTheme above MaterialApp or CupertinoApp
CustomTheme(
data: customThemeData,
child: MaterialApp(),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment