I want to create a recursive mixin in Dart. Here is what I've tried:
mixin A<T extends Object> on Object {
List<Object?> get list;
List<Object?> get _list => [if (super is A) ...super._list, ...list];
}
But this code gives me an info lint that tells me super
is always A
, but also ._list
is not defined in super
.
If I try and fix the second lint by doing this:
List<Object?> get _props => [if (super is A) ...(super as A)._props, ...props];
It gives me a new lint saying that super as A
is an unnecessary cast.
What I want to achieve here, is a Mixin
that when added to a base class, the _list
will have the same contents as the list
. But when I have an extended class from the base one, if I override the list
, this class _list
will have the base class list
added to the new one.
CodePudding user response:
You cannot treat super
as an object of its own in Dart, so what you are attempting is not possible, as you cannot ensure that there exists a super._list
property. That is what on
is normally for, but you cannot have a mixin depend on itself.
Some alternative ways to do this would be:
Make an abstract class that declares the
_list
property, and have classes that mix-in this mixin extend itMake including
super
's items the responsibility of the subclass, indicating this withpackage:meta
's@mustCallSuper
annotationThis is a common pattern for this type of additive usecase - Flutter widgets, for example, make heavy use of it.