Dart Mixins: Mixin in Code

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.
Mixin in 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();
}
//Output
Breathing // Output of dog.breathe()
Barking // Output of dog.bark()
.....Snake.....
Breathing // Output of snake.display()
Crawling // Output of snake.display()
Explanation
We create a mixin named
Barkusing thebark()method.We create a mixin named
Flyusing thefly()method.We create a mixin named
Crawlusing thecrawl()method.We create a class named
Animalusing thebreathe()method.We create a class named
Dogwhich extends theAnimalclass. TheDogclass uses thewithkeyword to access the method in theBarkmixin class.We create a class named
Batwhich extends theAnimalclass. TheBatclass uses thewithkeyword to access the method in theFlymixin class.We create a class named
Snakewhich extends theAnimalclass. TheDogclass uses thewithkeyword to access the method in theCrawlmixin class. In theSnakeclass, we create a method calleddisplay()which invokes the methods the class can implement.We create the
main()function. Inmain(), we create objects of theDogandSnakeclasses, which are “dog” and “snake” respectively. Finally, we use the objects created to invoke the methods.
Note: A mixin cannot be instantiated.



