Files
flutter-study-notebook/study_guide/Mixins in Dart.md
T

1.7 KiB

Mixins in Dart: A Comprehensive Guide

Mixins are a way of reusing a class's code in multiple class hierarchies. They allow you to add features to a class without inheritance.

1. Creating a Mixin

To create a mixin, use the mixin keyword followed by the mixin name.

Example:

mixin Logger {
  void log(String message) {
    print('Log: $message');
  }
}

2. Using a Mixin

To use a mixin, use the with keyword followed by the mixin name.

Example:

class User with Logger {
  String name;

  User(this.name);

  void greet() {
    log('Hello, $name!');
  }
}

void main() {
  var user = User('Alice');
  user.greet(); // Prints: Log: Hello, Alice!
}

3. Multiple Mixins

A class can use multiple mixins.

Example:

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

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

class Duck with Swimmer, Flyer {}

void main() {
  var duck = Duck();
  duck.swim(); // Prints: Swimming
  duck.fly();  // Prints: Flying
}

4. Mixin Inheritance

Mixins can inherit from other mixins using the on keyword.

Example:

mixin MusicalPerformer on Musician {
  void perform() {
    playInstrument();
    sing();
  }
}

class Musician {
  void playInstrument() => print('Playing instrument');
  void sing() => print('Singing');
}

class Singer extends Musician with MusicalPerformer {}

void main() {
  var singer = Singer();
  singer.perform();
  // Prints:
  // Playing instrument
  // Singing
}

Conclusion

Mixins provide a powerful way to reuse code across different class hierarchies. They are particularly useful for adding behavior to classes without the complexity of multiple inheritance.