Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator

What are mixins in Dart?

Maria Elijah

Dart mixins

A mixin is a class with methods and properties utilized by other classes in Dart.

It is a way to reuse code and write code clean.

To declare a mixin, we use the mixin keyword:

mixin Mixin_name{
 }

Mixins, in other words, are regular classes from which we can grab methods (or variables) without having to extend them. To accomplish this, we use the with keyword.

Let’s understand this better with a code example.

Code

The following code shows how to implement mixin in Dart.

// Creating a Bark mixin
mixin Bark {
  void bark() => print('Barking');
}

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

mixin Crawl {
  void crawl() => print('Crawling');
}
// Creating an Animal class
class Animal{
  void breathe(){
    print("Breathing");
  }
}
// Createing a Dog class, which extends the Animal class 
// Bark is the mixin with the method that Dog can implement
class Dog extends Animal with Bark {}

// Creating a Bat class Bat, which extends the Animal class
// Fly is the mixin with the method that Bat can implement
class Bat extends Animal with Fly {}

class Snake extends Animal with Crawl{
  // Invoking the methods within the display
  void display(){
    print(".....Snake.....");
    breathe();
    crawl();
  }
}

main() {
  var dog = Dog();
  dog.breathe();
  dog.bark();

  var snake = Snake();
  snake.display();

}
Using mixins in Dart

Explanation

  • Lines 2–4: We create a mixin named Bark using the bark() method.
  • Lines 6–8: We create a mixin named Fly using the fly() method.
  • Lines 10–12: We create a mixin named Crawl using the crawl() method.
  • Lines 14–18: We create a class named Animal using the breathe() method.
  • Line 21: We create a class named Dog which extends the Animal class. The Dog class uses the with keyword to access the method in the Bark mixin class.
  • Line 25: We create a class named Bat which extends the Animal class. The Bat class uses the with keyword to access the method in the Fly mixin class.
  • Lines 27–34: We create a class named Snake which extends the Animal class. The Dog class uses the with keyword to access the method in the Crawl mixin class. In the Snake class, we create a method called display() which invokes the methods the class can implement.
  • Lines 36–43: We create the main() function. In main(), we create objects of the Dog and Snake classes, which are “dog” and “snake” respectively. Finally, we use the objects created to invoke the methods.

Note: A mixin cannot be instantiated.

RELATED TAGS

dart
communitycreator
RELATED COURSES

View all Courses

Keep Exploring