Sobes.tech
Junior

What is a mixin in Dart or Flutter?

sobes.tech AI

Answer from AI

A mixin is a special type of class in Dart that allows you to incorporate functionality from one or more classes into another class without using traditional inheritance (multiple inheritance is not supported in Dart). They are used with the with keyword.

Main features:

  • Code reuse: Allows sharing code across different class hierarchies.
  • Extending functionality: A class can "accept" methods and properties from a mixin.
  • No extends for mixins: A class used as a mixin does not need to inherit from another class, but it cannot have constructors with parameters.
  • with syntax: Used with classes via the with keyword after extends (if the class inherits) or implements.

Example of defining a mixin:

// Mixins cannot have parameterized constructors
mixin LoggerMixin {
  void logMessage(String message) {
    print('LOG: $message');
  }
}

Example of using a mixin in a class:

class MyClass with LoggerMixin {
  void doSomething() {
    logMessage('Doing something'); // Using method from mixin
  }
}

void main() {
  var myObject = MyClass();
  myObject.doSomething();
}

Mixins are applied from right to left: if multiple mixins have methods/properties with the same name, the implementation from the rightmost mixin is used.