How do I check whether an object's class included a mixin? For example:
class AClass extends Object with MyMixin {}
class BClass extends Object {}
classIncludesMixin(new AClass(), 'MyMixin'); // => true
classIncludesMixin(new BClass(), 'MyMixin'); // => false
What should be in this classIncludesMixin()
method in order for it to work?
A mixin is a class with methods and properties utilized by other classes in Dart. It is a way to reuse code and write code clean. Mixins, in other words, are regular classes from which we can grab methods (or variables) without having to extend them. To accomplish this, we use the with keyword.
Mixin is a different type of structure, which can only be used with the keyword with. In Dart, a class can play the role of mixin if the class is does not have a constructor.
A mixin is a class whose methods and properties can be used by other classes – without subclassing. It's a reusable chunk of code that can be “plugged in” to any class that needs this functionality. Mixins are supported by Dart, and Flutter uses them in many places.
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 . In this way, your Car can run , but cannot be ' handleControlled '.
You can simply use a type check o is MyMixin
(that will be also true for inheritance and implementation).
If you really have to check the mixin clause you have to use dart:mirrors :
bool classIncludesMixin(o, String mixinName) {
var c = reflect(o).type;
while (c != null) {
var m = c.mixin;
if (c != m && m.simpleName == new Symbol(mixinName)) return true;
c = c.superclass;
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With