- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Mixins in Dart Programming
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 −
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
- Related Articles
- Comments in Dart Programming
- Constructors in Dart Programming
- Enumerations in Dart Programming
- Functions in Dart Programming
- Immutability in Dart Programming
- Inheritance in Dart Programming
- Iterables in Dart Programming
- Lists in Dart Programming
- Loops in Dart Programming
- Maps in Dart Programming
- Methods in Dart Programming
- Queue in Dart Programming
- Runes in Dart Programming
- Set in Dart Programming
- String in Dart Programming
