Mixins#
About#
- Mixins enable code reuse across hierarchies.
- Add capabilities without inheritance.
- Support multiple composition.
- Restricted using
onclauses.
Main Topics#
-
Basic Mixin
-
Definition:
mixinkeyword. -
Example:
mixin Logging { void log(String msg) => print(msg); }
-
Definition:
-
Usage
- **Definition
:with` keyword. -
Example:
class Controller with Logging {...}
- **Definition
-
Restrictions
- **Definition
:on` keyword. -
Example:
mixin Auth on Controller {...}
- **Definition
-
Multiple Mixins
- **Definition`: Linearization rules.
-
Example:
class App with A, B, C {...}
How to Use#
- Define: Create reusable behavior units
-
Compose: Apply with
withkeyword -
Restrict: Use
onfor requirements - **Order`: Last mixin takes precedence
How It Works#
- Linearization: Depth-first order
- **No Instantiation`: Can’t be constructed
- **No Constructors`: Only methods/properties
Example Session:
void main() {
var app = App();
app.log('Message'); // From Logging mixin
}
Conclusion#
Mixins provide flexible composition beyond inheritance, enabling orthogonal behavior reuse while maintaining clear ownership rules in Dart applications.