D
OOP & SOLIDMedium30 XP4 min read

What are mixins in Dart and how are they different from inheritance?

TL;DR: Mixins are reusable code units that can be applied to multiple classes using 'with'. They provide implementation without being a full parent class. Use 'on' to restrict which classes can use a mixin.

Full Answer

Dart is single-inheritance. Mixins solve the need to share behavior across unrelated class hierarchies without the diamond inheritance problem.

mixin vs abstract class

A mixin cannot be instantiated. It's applied to an existing class hierarchy. The 'on' constraint requires the mixin to be applied only to classes that extend/implement a specific type โ€” giving the mixin access to that type's API.

๐ŸŽฏ

Flutter's own TickerProviderStateMixin and AutomaticKeepAliveClientMixin are examples. TickerProviderStateMixin uses 'on State' to access the widget's lifecycle.

Code Examples

dartMixin with on constraint
Output
{id: q-001, type: Question}

Common Mistakes

  • โœ—Using extends when you need mixin behavior โ€” extends ties you to a parent class hierarchy
  • โœ—Forgetting that mixin application order matters โ€” rightmost mixin wins in case of method conflict

Interview Tip

๐Ÿ’ก

Flutter uses mixins heavily (TickerProviderStateMixin, KeepAliveClientMixin). Show you can explain 'on' constraint โ€” it's what enables mixins to access the base class's API safely.

#mixin#with#on#multiple-inheritance