What is the use of Mixins?

yourmdsarfaraj

MD Sarfaraj

Posted on September 1, 2022

What is the use of Mixins?

Hi guys, today I am going to share the use of mixins in dart programming. So before going to make any delay let’s start.

What is Mixins?

Dart does not support multiple inheritances, but Maxins gives us the ability to achieve multiple inheritances. To put it simply, mixins are classes that allow us to borrow methods and variables without extending the class. Dart uses a keyword called withfor this purpose.

For example,
We have a Car class and we want to access Brand and Model both clasess methods in Car class at this situation mixins give us the opportunity to achieve this using the keyword with.

Mixins example

class Brand {
  void getBrand({required String carBrand}) {
    print("Brand name : $carBrand");
  }
}

class Model {
  void getModel({required String carModel}) {
    print("Model : $carModel");
  }
}

class Car extends Brand with Model { //calling Brand and Model both classes at the same time 
  void getCarDetails({required String carBrand, required String carModel}) {
    print("Hey, here is my car details");
    getBrand(carBrand: carBrand);
    getModel(carModel: carModel);

  }
}

void main() {
  Car car = Car();
  car.getCarDetails(carBrand: 'Tex', carModel: '1976 Cadillac Coupe DeVille');
}

Enter fullscreen mode Exit fullscreen mode

It is my hope that you now understand the concept of mixins in Dart, thank you for reading.

💖 💪 🙅 🚩
yourmdsarfaraj
MD Sarfaraj

Posted on September 1, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Streams in Dart
dart Streams in Dart

September 29, 2023

What is the use of Mixins?
dart What is the use of Mixins?

September 1, 2022

Dart Basic Overview
dart Dart Basic Overview

December 15, 2020