-
Notifications
You must be signed in to change notification settings - Fork 56
injected_theme_api
It is very easy to dynamically switch the theme of your app. states_rebuilder offers a very simple API to handle app theming.
- InjectedTheme
- get the current theme
- Setting a theme
- toggle between light and dark theme
- set ThemeMode
- check the theme dark (isDarkTheme)
- get supported themes
- listen to theme change
Suppose our InjectedAuth
state is named theme
.
//Key is a generic type, it is the type of the
//keys of the lightThemes and darkThemes map.
InjectedTheme<Key> theme = injectTheme<Key>({
required Map<Key, ThemeData> lightThemes,
Map<Key, ThemeData>? darkThemes,
ThemeMode themeMode = ThemeMode.system,
String? persistKey,
//Similar to other injects
SideEffects? sideEffects,
SnapState<Key> Function(SnapState<Key> current, SnapState<Key> next ) stateInterceptor,
DependsOn<Key>? dependsOn,
int undoStackLength = 0,
bool autoDisposeWhenNotUsed = true,
bool isLazy = true,
String? debugPrintWhenNotifiedPreMessage,
})
This is a required parameter. It is a Map<Key, ThemeData>
. It maps the light themes the app supports.
Key
can be a simple string or enumeration.
The first Map Entry is taken as the default (fallback) one.
This is an optional parameter. Normally, there is a correspondence between the light and dark themes. Nevertheless, it is allowable to have a light theme that has no corresponded dark one.
Used to switch between dark, light, and system theme mode. The default value will be that of the system.
It is the key to be used to locally store the state of the theme. If defined the app will store the chosen theme and retrieve it on app start.
You have to first implement the IPersistStore
.
theme.lightTheme; // get current light theme
theme.darkTheme: // get current dark theme
theme.themeMode: // get current theme mode
To set the app to use a particular theme, you use:
//just mutate the state of the theme
theme.state = 'key';
theme.toggle();
theme.themeMode = ThemeMode.system;
theme.isDarkTheme();
example:
Switch(
value: theme.isDarkTheme,
onChanged: (_) => theme.toggle(),
)
theme.supportedLightThemes; //get a list of light supported themes
theme.supportedDarkThemes; //get a list of dark supported themes
To listen to the InjectedTheme state, we use the TopStatelessWidget
that must be on top of the MaterialApp
widget.
void main() {
runApp(MyApp());
}
class MyApp extends TopStatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: theme.lightTheme, //light theme
darkTheme: theme.darkTheme, //dark theme
themeMode: theme.themeMode, //theme mode
home: HomePage(),
);
}
}