Mixins
Mixins
About
- Mixins enable code reuse across hierarchies.
- Add capabilities without inheritance.
- Support multiple composition.
- Restricted using
on
clauses.
Main Topics
-
Basic Mixin
- Definition:
mixin
keyword. - 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
with
keyword - Restrict: Use
on
for 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.