Themes
Talking about themes here isn't quite what regular Flutter developers are accustomed to: global widget styles, color schemes, etc. Within Duit, themes are a powerful feature that solve several key challenges:
- Define a set of widget properties to be used throughout the application
- Reduce the size of screen layouts by isolating repetitive properties into themes
- Support design systems on the server side
How Themes Work
Applying themes to widgets involves several stages:
- Theme Initialization: Convert the JSON theme data into a tokenized
DuitThemeobject using theDuitThemePreprocessorclass and register it inDuitRegistry - Retrieve Theme Token: When creating widget attributes, the corresponding token is retrieved by the theme key
- Merge Attributes: The widget attributes object is merged with the theme token attributes according to merge rules
All this logic is executed automatically when creating a ViewAttribute instance via the ViewAttribute.from() method.
Theme Creation
Currently, DSL libraries lack specific classes or functions to help create and validate themes on the backend. A theme is represented as a hash table in the following format:
{
"text_bold": {
"type": "Text"
"data": {
"fontSize": 18.0,
"fontWeight": 700,
},
},
"text_secondary": {
"type": "Text"
"data": {
"fontSize": 14.0,
"fontWeight": 400,
},
},
"col_space_btw": {
"type": "Column",
"data": {
"mainAxisAlignment": "spaceBetween",
},
},
"custom_widget_theme1": {
"type": "CustomWidgetTagInsteadOfWidgetType",
"data": {
"some_property": "some_value",
},
},
}
The keys of the hash table are theme names. Names must be unique, but you can create an unlimited number of themes for widgets of the same type.
The values of the hash table are objects that represent theme tokens, which consist of type — the widget type for which a specific theme will be used — and data — the widget attribute object.
Themes are supported for custom widgets as well.
For a theme to be correctly applied to widget attributes, the type property must contain the custom widget's tag, not its base type (Custom).
Theme Initialization
Creating and Initializing a Theme
To work with themes in Duit, you need to:
- Convert theme JSON data into a tokenized
DuitThemeobject using theDuitThemePreprocessorclass - Initialize the theme in the registry via the
DuitRegistry.initialize()method
// Example: loading a theme from JSON and initializing
Future<void> initTheme() async {
// Option 1: theme from local JSON
final themeData = jsonDecode(await rootBundle.loadString('assets/theme.json'));
// Option 2: theme from server
// final res = await dio.get('/theme');
// final themeData = res.data;
final preprocessor = const DuitThemePreprocessor();
final theme = preprocessor.tokenize(themeData);
await DuitRegistry.initialize(theme: theme);
}
After obtaining the JSON data containing the theme, use the DuitThemePreprocessor class to perform tokenization (converting MapEntry into instances of the ThemeToken class).
Theme Tokens
Tokens are special objects that store widget attributes to be used when merging attribute objects with theme attributes. They are employed to provide greater flexibility in validating incoming parameters during theme processing.
abstract class ThemeToken {
final Set<String> excludedFields;
final Map<String, dynamic> _data;
final String type;
Map<String, dynamic> get widgetTheme => _data;
const ThemeToken(
this.excludedFields,
this._data,
this.type,
);
}
Pay close attention to the Set<String> excludedFields property.
This set contains the names of fields that should not be included in the widget's theme attributes.
The tokenization mechanism validates incoming attributes to ensure they conform to expectations.
If a property is found in the excludedFields set, an exception will be thrown.
Built-in Token Types
DuitThemePreprocessor supports many built-in token types:
- TextThemeToken - for
Texttype widgets - ImageThemeToken - for
Imagetype widgets - AttendedWidgetThemeToken - for stateful widgets (Checkbox, Switch, TextField)
- AnimatedPropOwnerThemeToken - for widgets owning animated properties
- ImplicitAnimatableThemeToken - for widgets with implicit animations
- ExcludeGestureCallbacksThemeToken - for gesture widgets (GestureDetector, InkWell)
- ExcludeChildThemeToken - for widgets excluding child elements from themes (AppBar, Scaffold)
- DynamicChildHolderThemeToken - for widgets with dynamic children (GridView, ListView)
- RadioThemeToken, RadioGroupContextThemeToken - for radio buttons
- SliderThemeToken - for sliders
- RichTextThemeToken - for rich text
For all other widget types, DefaultThemeToken is used.
Extending and Overriding Preprocessor Behavior
There are two ways to extend preprocessor behavior within the implementation:
customWidgetTokenizer- Add handling for a new widget type to the preprocessor. Useful when you want to introduce unsupported widget themes or apply themes to custom widgets.overrideWidgetTokenizer- Override token creation for a specific widget type. Useful when you want to modify the list of excluded fields for a built-in widget.
In both cases, you should return an instance of the ThemeToken class or null if you don't want to override behavior. You can also create your own ThemeToken classes for convenience.
// Create a token for a custom widget
final class CustomWidgetThemeToken extends ThemeToken {
CustomWidgetThemeToken(Map<String, dynamic> data)
: super(
const {}, // allow all fields
data,
"ExampleCustomWidget",
);
}
// Override token for built-in Text widget
final class OverrideTextThemeToken extends ThemeToken {
OverrideTextThemeToken(Map<String, dynamic> data)
: super(
const {"data"}, // disallow "data" field
data,
"Text",
);
}
// Usage in preprocessor
Future<void> initThemeWithCustomTokens() async {
final preprocessor = DuitThemePreprocessor(
// Add handling for a new token
customWidgetTokenizer: (type, themeData) {
switch (type) {
case "ExampleCustomWidget":
return CustomWidgetThemeToken(themeData);
}
return null;
},
// Override handling for built-in widget
overrideWidgetTokenizer: (type, themeData) {
switch (type) {
case "Text":
return OverrideTextThemeToken(themeData);
}
return null;
},
);
final theme = preprocessor.tokenize(themeData);
await DuitRegistry.initialize(theme: theme);
}
In the above code example, we created a preprocessor with customizable tokenization logic for custom and built-in widgets.
Using Themes in DSL Libraries
Several new optional properties have been introduced for many widgets implemented in DSL libraries, allowing you to configure widgets for theme usage. These properties are defined in the ThemeConsumer interface.
- TypeScript
- Go
export interface ThemeConsumer {
theme?: string;
ignoreTheme?: boolean;
overrideRule?: keyof typeof ThemeOverrideRule;
}
type ThemeConsumer struct {
Theme string `json:"theme,omitempty"`
IgnoreTheme bool `json:"ignoreTheme,omitempty"`
OverrideRule ThemeOverrideRule `json:"overrideRule,omitempty"`
}
ThemeConsumer Properties
theme- a string key representing the unique name of the theme token you want to apply to the widget.ignoreTheme- indicates whether a specific widget should ignore the specified theme. By default, it is set tofalse.overrideRule- defines how theme attributes are merged with widget attributes.
Merge Rules (overrideRule)
The overrideRule property can take two values:
themeOverlay(default) - theme applies to existing widget properties but does not overwrite them. If a widget has a property that also exists in the theme, the widget's value takes priority.themePriority- theme takes priority over widget properties. If a widget has a property that also exists in the theme, the theme's value will overwrite the widget's value.
Usage Example
- TypeScript
- Go
const textWidget: TextAttributes = {
data: "Hello World",
theme: "text_primary",
overrideRule: "themeOverlay", // property data won't be overwritten
textAlign: "center"
};
textWidget := &TextAttributes{
Data: "Hello World",
ThemeConsumer: &ThemeConsumer{
Theme: "text_primary",
OverrideRule: ThemeOverlay,
IgnoreTheme: false,
},
TextAlign: duit_props.TextAlignCenter,
}
In this example, if the text_primary theme contains fontSize: 18 and color: "#FF0000", the widget will receive these properties, but its own properties (e.g., textAlign: "center" and data: "Hello World") will be preserved.
Theme Merge Mechanism
When creating widget attributes, the widget's properties are merged with the theme attributes:
Merge Algorithm
- Check
ignoreThemeflag: IfignoreTheme = true, theme application is skipped. - Retrieve theme token: The theme token is retrieved by the
themekey fromDuitRegistry. - Type check: The token is applied only if its type matches the widget type.
- Merge attributes depending on
overrideRule:themeOverlay:{...token.widgetTheme, ...widgetAttributes}- widget properties overwrite theme propertiesthemePriority:widgetAttributes.addAll(token.widgetTheme)- theme properties overwrite widget properties
Examples
Consider an example of the merge mechanism:
{
"text_primary": {
"type": "Text",
"data": {
"fontSize": 18.0,
"fontWeight": 700,
"color": "#FF0000"
}
}
}
Example 1: themeOverlay (default)
Widget:
{
"type": "Text",
"data": "Hello",
"theme": "text_primary",
"textAlign": "center"
}
Merge result:
{
"data": "Hello",
"textAlign": "center",
"fontSize": 18.0,
"fontWeight": 700,
"color": "#FF0000"
}
Example 2: themePriority
Widget:
{
"type": "Text",
"data": "Hello",
"theme": "text_primary",
"overrideRule": "themePriority",
"textAlign": "center"
}
Merge result:
{
"data": "Hello",
"textAlign": "center",
"fontSize": 18.0,
"fontWeight": 700,
"color": "#FF0000"
}