Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 61 ยท Classes and Object-Oriented Dart

Mixins

Learn how Dart mixins share behavior across unrelated classes: the mixin and with keywords, on constraints, mixin class, and the order in which mixins stack.

Single inheritance is simple but limiting. A Duck and a Plane can both fly, yet they have no sensible common parent. An interface would force you to write fly() twice. What you want is to write the flying code once and attach it to both classes. In Dart that tool is the mixin: a bundle of fields and methods that classes can "mix in" without extending anything.

This lesson covers declaring a mixin, using it with with, restricting it with on, the Dart 3 mixin class, and how several mixins combine (linearization). Dart code is read-only; the stand-ins use the TypeScript mixin pattern, a function that takes a class and returns a bigger class.

Declaring and using a mixin

A mixin is declared with the mixin keyword. It can have fields, methods, getters and setters, but no constructor and no extends clause.

DART
mixin Swimmer {
  int depth = 0;

  void dive(int meters) {
    depth += meters;
    print('diving to $depth m');
  }
}

mixin Flyer {
  void fly() => print('flying');
}

class Animal {
  final String name;
  Animal(this.name);
}

class Duck extends Animal with Swimmer, Flyer {
  Duck(super.name);
}

class Plane with Flyer {}

void main() {
  var duck = Duck('Donald');
  duck.dive(2);     // diving to 2 m
  duck.fly();       // flying
  Plane().fly();    // flying
}

with goes after extends and lists one or more mixins. The class gets every member of every mixin, as if the code had been pasted in. The mixin's type also becomes a supertype: a Duck is an Animal, a Swimmer and a Flyer, so Flyer f = Duck('Donald'); is valid.

Mixins solve a different problem from abstract classes and interfaces. An interface shares only a signature, whereas a mixin shares the implementation. Compared with inheritance, a class can use many mixins but extend only one parent.

flowchart TD
    A["Animal"] --> D["Duck"]
    S["mixin Swimmer"] -.->|with| D
    F["mixin Flyer"] -.->|with| D
    F -.->|with| P["Plane"]

Duck extends Animal and mixes in Swimmer and Flyer; Plane reuses Flyer without any shared parent.

TypeScript One behavior, two unrelated classes (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Restricting a mixin with on

Some mixins only make sense on certain classes. Perhaps a Walker needs the legs count from its host. The on clause declares that the mixin may only be applied to subclasses of a given type, and in return, the mixin can use that type's members, even call super.

DART
abstract class Creature {
  int get legs;
}

mixin Walker on Creature {
  String walk() => 'walking on $legs legs';
}

class Dog extends Creature with Walker {
  @override
  int get legs => 4;
}

// class Rock with Walker {}   // error: Rock is not a Creature

The on type is a requirement, not an inheritance: the mixin does not extend Creature. It only says "whoever uses me already is one". This lets the mixin call legs safely, because the compiler knows every user has it.

Linearization: what happens with several mixins

When a class applies several mixins, Dart stacks them from left to right. Each mixin is applied on top of the previous result, so the last one listed is the closest to the class and wins when two mixins define the same method. A super.method() call inside a mixin goes to the next layer down.

DART
class Base {
  String who() => 'Base';
}

mixin A on Base {
  @override
  String who() => 'A > ${super.who()}';
}

mixin B on Base {
  @override
  String who() => 'B > ${super.who()}';
}

class C extends Base with A, B {}

void main() {
  print(C().who());      // B > A > Base
}

Reading the chain: C calls B.who, whose super is the combination of Base with A, whose super is Base. If you wrote with B, A the output would be A > B > Base. The order matters whenever mixins override the same member, so it is a good habit to give each mixin a separate responsibility, and to keep mixins small.

flowchart LR
    C["C"] --> B["B"]
    B --> A["A"]
    A --> Base["Base"]

The chain of super calls for class C extends Base with A, B: B first, then A, then Base.

TypeScript Mixin order decides who runs first (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Mixin classes (Dart 3)

Before Dart 3, any class without a constructor could double as a mixin. Dart 3 made this explicit: an ordinary class can no longer be used after with. If you want something that works both as a class and as a mixin, declare a mixin class:

DART
mixin class Logger {
  void log(String message) => print('[log] $message');
}

class Service with Logger {
  void run() => log('running');
}

class Standalone extends Logger {}      // also usable as a normal class

A mixin class cannot declare a generative constructor or have an extends, with or on clause, because it must be usable as a mixin. For pure mixins use mixin and keep it simple. You can also add the base modifier, base mixin Logger, to prevent others from implementing it; see Class Modifiers: sealed, final, base.

Good and bad uses

Mixins shine for cross-cutting abilities: logging, equality helpers, caching, event handling, validation, "can be disposed". Flutter uses them everywhere, for example for animation tickers. They are a poor choice for a deep "is a" hierarchy; use inheritance there. Watch out for state: a mixin with fields adds hidden storage to every class that uses it, and two mixins that declare the same field name will clash. And remember that a mixin cannot take constructor parameters, so configuration usually arrives through abstract getters or methods that the host class implements.

Do not reach for a mixin just to avoid writing a helper function. If the code needs no access to the object's state, a plain top-level function or an extension method is simpler.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which keyword attaches a mixin to a class?

    class Duck extends Animal with Swimmer applies Swimmer to Duck. The mixin keyword only declares one.
  2. 2. What can a mixin declaration NOT have?

    Mixins cannot declare constructors, because they are never instantiated or extended in the normal way.
  3. 3. What does mixin Walker on Creature mean?

    The on clause restricts which classes can use the mixin and lets the mixin rely on the members of that type.
  4. 4. Given class C extends Base with A, B, which mixin's method is found first?

    The last mixin in the list is applied last, so it sits closest to the class and its override runs first.
  5. 5. Since Dart 3, how do you make a type usable both as a class and as a mixin?

    Ordinary classes can no longer follow with. A mixin class is explicitly both.

Summary

  • A mixin bundles fields and methods that classes reuse with with, without a shared parent.
  • A class has one superclass but can apply many mixins; a mixin cannot have a constructor.
  • mixin M on T limits the mixin to subclasses of T and gives it access to T's members and super.
  • With several mixins, the last one listed wins, and super calls travel down the chain.
  • mixin class is both a class and a mixin; ordinary classes cannot be mixed in since Dart 3.

Next, control exactly how a library's types can be extended in Class Modifiers: sealed, final, base.