Check Mobile App
Read now
Start a Project

Using Mixins in Flutter


In this article, we are going to use Dart’s Mixins in Flutter.

What are mixins?

Mixins are a way of reusing a class’s code in multiple class hierarchies. They provide an elegant way to reuse code from different classes that don’t quite fit into the same class hierarchy.

Mixin allows dart developers to use methods and properties which are not defined in the same class – without subclassing or extending the other class.

Mixin is an awesome and powerful feature of dart because it solves a basic problem that comes with inheritance or subclassing.

Use case: For example, you might have a class called Vehicle which has a method named run(). The code in the above class may be useful for both Car and MotorBike. But, now imagine you’re introducing a class called MotorBoat. You probably have some functionality on MotorBike (such as a method called handleControlled()) that you’d like to use in the MotorBoat, but not that you want to add to Vehicle. This is a great place to use a mixin called MotorVehicle.

Using Mixins in Flutter

To implement a mixin, create a class that extends Object and declares no constructors. Unless you want your mixin to be usable as a regular class, use the mixin keyword instead of class

To use a mixin, use the with keyword followed by one or more mixin names. For example:

In this way, your Car can run, but cannot be ‘handleControlled‘. Both MotorBike and MotorBoat can do both, and the MotorBoat can runOnWater.

Sometimes you might want to restrict the types that can use a mixin. You can restrict a mixin’s use by using the on keyword to specify the required superclass. The on keyword describes which inheritance structure the mixin can be used on. For example:

In the preceding code, only classes that extend or implement the MotorBike class can use the mixin MotorVehicle. Because SportsMotorBike extends MotorBikeSportsMotorBike can mix in MotorVehicle.

Thanks for reading.

Happy Coding 🙂

For more Flutter tutorials visit: Mobikul Blogs

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.


Great Product, Great Team, and Great Support Service. And if you want to add more features to the product, they can submit any idea that comes to your mind. They really care about their clients and we are really happy and honored to deal with Webkul.

Talk to Sales


Live Chat
Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home