DEV Community

MD Sarfaraj
MD Sarfaraj

Posted on

1

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.

Sentry mobile image

Is your mobile app slow? Improve performance with these key strategies.

Improve performance with key strategies like TTID/TTFD & app start analysis.

Read the blog post

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay