Mixins in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

Mixins in Dart are a way of using the code of a class again in multiple class hierarchies. We make use of the with keyword followed by one or more mixins names.

Mixins can be used in two ways, the first case is when we want to make use of class code in such a way that the class doesn't have any constructor and the object of the class is extended. In such a case, we use the with keyword.

Another case is when we want our mixin to be usable as a regular class, then we make use of the mixin keyword instead of class.

Now, let's create different classes in Dart, where one is a simple class named Perimeter and the other is a mixin whose body code we will make use of.

Example

Consider the example shown below −

 Live Demo

import 'dart:math';

class Position {
   int x;
   int y;

   double distanceFrom(Position dis) {
      var dx = dis.x - x;
      var dy = dis.y - y;
      return sqrt(dx * dx + dy * dy);
   }
}

class Perimeter {
   int length;
   int breadth;

   int get area => 2 * (length * breadth);
}

class PerimeterView extends Perimeter with Position {}

void main() {
   var origin = new Position()
      ..x = 0
      ..y = 0;

   var p = new PerimeterView()
      ..x = 5
      ..y = 5
      ..length = 10
      ..breadth = 11;

   print(p.distanceFrom(origin));
   print(p.area);
}

It should be noted that we are making use of the mixin when we are extending the Perimeter class along with our mixin which is Position.

Output

7.0710678118654755
220
raja
Published on 21-May-2021 13:12:04
Advertisements