๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Dart Mixins

A mixin is a bundle of methods that many classes can take in. A class takes in a mixin with the word with.

The same method written twice

Duck and Fish each carry a copy of the same swim method. The copies do the same job in two places.

class Duck {
  void swim() {
    print('Swimming');
  }
}

class Fish {
  void swim() {
    print('Swimming');
  }
}

void main() {
  var duck = Duck();
  duck.swim();
  var fish = Fish();
  fish.swim();
}

One mixin holds the method

The mixin holds swim in one place. Duck takes Swimmer in with the word with and gains the method.

mixin Swimmer {
  void swim() {
    print('Swimming');
  }
}

class Duck with Swimmer {}

void main() {
  var duck = Duck();
  duck.swim();
}

Two classes share one mixin

Duck and Fish both take in Swimmer. Each class gains swim from the single mixin definition.

mixin Swimmer {
  void swim() {
    print('Swimming');
  }
}

class Duck with Swimmer {}

class Fish with Swimmer {}

void main() {
  var duck = Duck();
  duck.swim();
  var fish = Fish();
  fish.swim();
}

A class keeps its own methods

Duck gains swim from Swimmer and keeps its own callOut method. Both methods run on the same object.

mixin Swimmer {
  void swim() {
    print('Swimming');
  }
}

class Duck with Swimmer {
  void callOut() {
    print('Quack');
  }
}

void main() {
  var duck = Duck();
  duck.swim();
  duck.callOut();
}

Example

mixin Swimmer {
  void swim() {
    print('Swimming');
  }
}

mixin Walker {
  void walk() {
    print('Walking');
  }
}

class Duck with Swimmer, Walker {}

class Fish with Swimmer {}

void main() {
  var duck = Duck();
  duck.swim();
  duck.walk();
  var fish = Fish();
  fish.swim();
}

Key points

  • mixin: a keyword that starts a mixin definition.
  • Use with to add a mixin to a class.
  • A mixin holds methods that more than one class can use.
  • The same mixin can go into classes that share no parent class.
  • A class can take in more than one mixin in one list.

In this example, Swimmer holds swim and Walker holds walk. Duck takes in both mixins, so duck can swim and walk. Fish takes in Swimmer only, so fish can swim. The prints show Swimming, Walking, and Swimming in that order.

Note

A class gains mixin methods without extending the mixin.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

Which word adds a mixin to a class?