IntermediateDart Questions

What are mixins in Dart and when would you use one?

Short Answer

A mixin lets a class reuse a chunk of behavior from multiple sources without using multiple inheritance — you declare it with `mixin` and apply it with `with`.

Dart classes can only extend one superclass, but a class can mix in several mixins, each contributing methods and fields. This is useful for cross-cutting behavior that doesn't fit a single inheritance hierarchy — for example, a `Validatable` mixin that adds validation logic to several unrelated form-field classes.

You can restrict which classes are allowed to use a mixin with the `on` clause (e.g. `mixin Flying on Animal`), which lets the mixin call methods it assumes the host class provides. Unlike a regular class, a mixin generally can't have its own constructor.

Code Example

mixin Loggable {
  void log(String message) => print('[LOG] $message');
}

class ApiClient with Loggable {
  void fetch() {
    log('Fetching data...');
  }
}

Common Mistakes

  • ×Confusing mixins with abstract classes — a mixin can't be instantiated directly with `new`/a constructor call.
  • ×Overusing mixins for things that would be clearer as plain composition (passing in a dependency instead of mixing in behavior).