What is the difference between class and mixin in dart?
Asked Answered
F

2

5

What is the difference between:

class A {}

class B with A{}

and

mixin A{}

class B with A{}

?

Flyback answered 5/5, 2022 at 20:15 Comment(1)
In that case, nothing. Classes that satisfy certain restrictions can be used either as classes or as mixins. That's not true for classes in general (e.g. a class with a constructor). To better understand how mixins work, I recommend reading lrn's explanation.Arian
M
5

In Dart, a class can only extend one other class. But it can implement or mixin as many as you want. The thing is, when you extend a class, you inherit all its attributes, methods and it's constructors. When you implement a class, if you are adding only methods/attributes that you don't already have, you can simply continue your code. If you are implementing an abstract method, you'll need to actually implement it. Now, mixins are like extended classes, the classes that mix them, are their child as well as with extend and implements, but it has no constructor.

The actual idea for mixins is that you can add functionalities to any class, and they don't have to extend another class. That's why they usually do simple stuff only.

Michelson answered 5/5, 2022 at 20:28 Comment(0)
V
1
/*normal class u can create constructors create objects from it 
 and all that good jazz*/

class Foo {
  final int a;
  Foo(this.a);
  void someMethod() {}
}
/*mixin is like a container than hold some 
  functionalities that you want to mix with an existing class*/

mixin Bar {
  void add() {}
}

/* this class extends Foo to inherent some goodness but i need a 
 functionality that is not directly related to parent child 
 relationship so i mix it with Bar */

class Baz extends Foo with Bar {
  Baz(super.a);

  void myMethod() {
    // i have access to add function here
    add();
  }
}

// mixin class act like both
mixin class AnotherClass {
  AnotherClass();
}
Vivisection answered 20/10 at 22:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.