CodeBlanks Logo Icon CodeBlanks

mixin constraints

Learn mixin constraints with on.

The on constraint

Sometimes you want a mixin to apply only to a certain kind of class. The on keyword constrains a mixin to a supertype; the mixin can only be applied to classes that extend that type.

Example: mixin Walker on Animal { void walk() { print('$name walking'); } }. Here the Walker mixin can only be applied to classes that extend Animal. This lets the mixin body safely reach the name field of Animal. Without the constraint, the mixin can be applied to any class but cannot use the supertype's members.

on and safe access

The on constraint does not only limit application; it also grants the mixin body access to the supertype's members. This makes the mixin safe and meaningful.

Example: the Walker on Animal mixin uses the name field of Animal. Without the on Animal constraint, reaching name in the mixin body would be a compile error. The constraint tells the compiler this mixin only runs on Animal derivatives; the name field always exists. As a result the mixin code runs safely and correctly.

Practice Write the Walker mixin with on

Define a class named Animal; add a String name field and an Animal(this.name) constructor. Declare mixin Walker on Animal; add a void walk() { print('$name walking'); } method. Write a class named Dog that extends Animal and applies the Walker mixin: class Dog extends Animal with Walker { Dog(String name) : super(name); }. In main, create an instance with var d = Dog('Rex'); and call d.walk().

Starter code

main.dart
// Define the Animal class
// Define the Walker mixin with on Animal
// Write the Dog class extending Animal + Walker

void main() {
  // Create a Dog('Rex') instance and call walk()
}

Sample solution

main.dart
// Define the Animal class
class Animal {
  String name;
  Animal(this.name);
}

mixin Walker on Animal {
  void walk() {
    print('$name walking');
  }
}

class Dog extends Animal with Walker {
  Dog(String name) : super(name);
}

void main() {
  var d = Dog('Rex');
  d.walk();
}

Expected output

Rex walking

Questions and answers

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

1 Match the on parts

Term Meaning
on Constraint keyword
Animal Supertype
Walker Mixin name

2 Add the on constraint

Question
mixin Walker ____ Animal {
  void walk() {
    print('$name walking');
  }
}
Answer
mixin Walker on Animal {
  void walk() {
    print('$name walking');
  }
}

Explanation: on constrains the mixin to a supertype.

3 What does mixin Walker on Animal provide?

  • Walker becomes a subclass of Animal
  • Walker can only be applied to classes that extend Animal Correct answer
  • Walker is automatically applied to all classes
  • Walker gains a constructor

Explanation: The on constraint limits the mixin to a specific kind of class.

All lessons in Intermediate