Mixins

Mixins

About

  • Mixins enable code reuse across hierarchies.
  • Add capabilities without inheritance.
  • Support multiple composition.
  • Restricted using on clauses.

Main Topics

  1. Basic Mixin

    • Definition: mixin keyword.
    • Example:
      mixin Logging {
        void log(String msg) => print(msg);
      }
  2. Usage

    • **Definition: with` keyword.
    • Example:
      class Controller with Logging {...}
  3. Restrictions

    • **Definition: on` keyword.
    • Example:
      mixin Auth on Controller {...}
  4. 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.