MIXINS IN DART(Flutter)

MIXINS IN DART(Flutter)

In Dart, mixins are a way to reuse code across different class hierarchies. A mixin is a class that provides a set of methods and properties that can be easily added to other classes without the need for inheritance. It allows you to compose behavior into a class without creating a full-blown inheritance relationship.

To define a mixin in Dart, you can use the mixin keyword followed by the mixin's name. Here's an example:

// 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
Barking
.....Snake.....
Breathing
Crawling

Note: A mixin cannot be instantiated.

You can use multiple mixins by separating them with commas.When a class uses multiple mixins, the members of the mixins are applied in the order they are listed.

It's important to note that mixins cannot have constructors, and they cannot be instantiated on their own. They are intended to be used as a composition mechanism for adding functionality to classes.

By using mixins, you can modularize and reuse code more effectively, promoting code reusability and maintaining a clean class hierarchy.

THANK YOU!