Adding features to a class: mixins

Mixins are a way of reusing a class’s code in multiple classhierarchies.

To use a mixin, use the with keyword followed by one or more mixinnames. The following example shows two classes that use mixins:

  1. class Musician extends Performer with Musical {
  2. // ···
  3. }
  4.  
  5. class Maestro extends Person
  6. with Musical, Aggressive, Demented {
  7. Maestro(String maestroName) {
  8. name = maestroName;
  9. canConduct = true;
  10. }
  11. }

To implement a mixin, create a class that extends Object anddeclares no constructors.Unless you want your mixin to be usable as a regular class,use the mixin keyword instead of class.For example:

  1. mixin Musical {
  2. bool canPlayPiano = false;
  3. bool canCompose = false;
  4. bool canConduct = false;
  5. void entertainMe() {
  6. if (canPlayPiano) {
  7. print('Playing piano');
  8. } else if (canConduct) {
  9. print('Waving hands');
  10. } else {
  11. print('Humming to self');
  12. }
  13. }
  14. }

To specify that only certain types can use the mixin — for example,so your mixin can invoke a method that it doesn’t define —use on to specify the required superclass:

  1. mixin MusicalPerformer on Musician {
  2. // ···
  3. }

Version note: Support for the mixin keyword was introduced in Dart 2.1. Code in earlier releases usually used abstract class instead. For more information on 2.1 mixin changes, see the Dart SDK changelog and 2.1 mixin specification.