CodeBlanks Logo Icon CodeBlanks

Multiple mixins

Learn to apply multiple mixins.

Multiple mixins

A class can apply many mixins, separated by commas. This shows Dart's power to combine behaviors; the single inheritance limit is overcome.

Example: class Duck with Flyer, Swimmer { ... }. Here the Duck class applies both the Flyer and the Swimmer mixin. Methods of both mixins are reachable on an instance: Duck().fly() and Duck().swim(). The mixin list is read left to right; the leftmost is applied first. When two mixins share a method name, the rightmost (last applied) wins.

Application order

The mixin list is applied left to right; order matters. When two mixins share a method name, the rightmost mixin wins and overrides the previous one.

Example: class A with M1, M2. Here M1 is applied first, then M2. If both define hello(), the class calls M2.hello(); M1.hello() is hidden. This behavior is how priority is set in behavior composition. Changing the order changes the results; this is why mixin list design needs care.

Practice Apply two mixins to Duck

Define two mixins named Flyer and Swimmer. In Flyer add a void fly() { print('Flying'); } method, in Swimmer add a void swim() { print('Swimming'); } method. Write a class named Duck: class Duck with Flyer, Swimmer { Duck(); }. In main, create an instance with var d = Duck(); and call d.fly() and d.swim().

Starter code

main.dart
// Define the Flyer and Swimmer mixins
// Apply both mixins to the Duck class

void main() {
  // Create a Duck instance and call fly() and swim()
}

Sample solution

main.dart
// Define the Flyer and Swimmer mixins
mixin Flyer {
  void fly() {
    print('Flying');
  }
}

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

class Duck with Flyer, Swimmer {
  Duck();
}

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

Expected output

Flying
Swimming

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is class Duck with Flyer, Swimmer { } written?

  • class Duck with Flyer; Swimmer { }
  • class Duck extends Flyer implements Swimmer { }
  • class Duck with Flyer, Swimmer { } Correct answer
  • class Duck with Flyer with Swimmer { }

Explanation: Multiple mixins are separated by commas.

2 Match the multiple mixin parts

Term Meaning
, List separator
Flyer, Swimmer Mixin list
Duck Class name

3 Add the second mixin

Question
class Duck with Flyer____ Swimmer {
  Duck();
}
Answer
class Duck with Flyer, Swimmer {
  Duck();
}

Explanation: A comma separates the mixin list.

All lessons in Intermediate