Utility-First Approach
Mix Utilities are essential for efficient and intuitive styling. This functional approach not only enhances the consistency of UI designs but also ensures a more intuitive styling process.
Key Concept
The Utility-First Approach focuses on crafting small, reusable style components like color variations, borders, radii, and spacing. These components can be seamlessly combined to form complex styles. This method encourages a modular approach to UI development, significantly reducing code duplication and enhancing flexibility.
Purpose & Benefits
- Semantic Consistency: Facilitates meaningful and easily understandable styling for widgets.
- Increased Efficiency: Streamlines development by simplifying code and improving maintainability.
- Enhanced Control: Offers greater command over styling, enabling better composability and integration of design elements.
Descriptive Styling
Utilities are designed to be descriptive and easy to understand. This makes it easy to know what each utility does and how to use it.
final style = Style(
width(100),
padding(10),
alignment.center(),
background.color.red(),
);
Intuitive API design
A utility is a class that mimics the functionality of a method. This allows you to use utilities in a way that feels natural and intuitive.
As there are many ways to use an utility to achieve the same result, normally they are done for different purposes, but they all achieve the same result, and you can use the one that makes more sense for you.
// Chaining style is the most common way to use utilities.
box.alignment.center();
// As this seems similar to the above, this allows you to pass an `Alignment` as a parameter.
box.alignment(Alignment.center);
// Gives you direct control over the `x` and `y` values of an `Alignment` object.
box.alignment.only(x: 0.0, y: 0.0);
Utility Aliases
Aliases are utilities that are meant to be used as a shorthand for other utilities, or provide a shortcut to a nested utility path.
Example
border
is an alias to box.border
which itself is an alias to box.decoration.border
. This allows you to use border
instead of box.decoration.border
to apply a border to a widget.
// A utility to define a box border.
border.color.red();
// The same as
box.decoration.border.color.red();
Creating aliases
If you want to create your own short hand utilities you can just assign the utility to a variable. For example:
// Custom alias for border top styling
final bt = border.top;
// As a method
bt.color.red();
// As a paramter
bt(color: Colors.red);
You can also create aliases for specific values of a utility. For example:
// Custom alias for alignment.center
final borderRedTop = border.top.color.red;
// Usage
borderRedTop();