Dart: mixins

 

Mixins in Dart

The mixin keyword was introduced in dart 2.1 and it is analogous to abstract class in some ways and different from it in other way. Like abstract class, you can declare abstract methods in mixins and it cannot be instantiated. But unlike abstract , you can’t extend a mixin.

Image for post

You can either use the keyword mixin, abstract class or a normal class as a mixin. Let’s take a look at how we can solve the above problem with mixins.

Always keep in mind that mixin is not multiple inheritance instead they are just a way to reuse our code from a class in multiple hierarchies without needing to extend them. Its like being able to use other people assets without being their children

When mixing classes, the classes used as mixins are not parallel but instead on top of the class using it. This is the reason why methods do not conflict with one another, allowing us to use codes from multiple classes without having to deal with the vulnerabilities of multiple inheritance.

If you are confused by this, don’t panic, I will explain how mixins are evaluated.

For determining which class method will be executed when using mixins, follow these simple steps:

  • If the class using mixins is extending any class then put that class on top of the stack. i.e class Musician extends Performer
  • Always remember the order in which you declare mixins, this is very important because it decides which class is more important. If mixins contains identical methods then the mixin class that is declared later will be executed(Declaring a mixin after another raises its “Importance”).

In our example, we declared Dancer before the Singer, so it is more “Important”and therefore would go below Performer . I.e class Musician extends Performer with Dancer

  • After Dancer we declared Singer , so put the Singer below Dancer in the stack :
  • Finally, add the class which is using mixins i.e Musician into the stack. This class would be the most important or most specific class.If this class contains any identical methods to mixins or super class then the methods in this class would be called first…always.

Comments

Popular posts from this blog

Flutter: Exploring more widgets

Flutter: Everything is a widget

Food Delivery App 5 - Firebase Storage for Profile Picture