TobiHeidi
TobiHeidi

Reputation: 1241

Dart Mixin get super field value

Based on a class and a mixin

class CounterModel extends MVAModel with CounterModelGeneratedCode {
  int counter = 2;
}

mixin CounterModelGeneratedCode on MVAModel {

int get counter => store.get("counter", () => (super as CounterModel).counter);
set counter(int value) => store.set("counter", value);
}

The dart analyzer does not complain but on compilation I get an

Error: Can't use 'super' as an expression. To delegate a constructor to a super constructor, put the super call as an initializer.

How can I access the overshadowed values of the CounterModel class (e.g. 2 for counter)?

Upvotes: 1

Views: 402

Answers (1)

lrn
lrn

Reputation: 71713

You cannot do that, and the analyzer should have caught the syntax error too. You cannot override the resolution of super-invocations, you can only call the actual superclass member. Also, the counter is not on the superclass, which is MVAModel, so using super is not the right approach.

You could try (this as CounterModel).counter, which would work, but it isn't optimal. The cast is not necessary, we can do better.

What you probably want in this case is to add a definition of the counter variable to the mixin declaration:

 abstract int counter;

That way, it requires classes mixing it in to define such a counter (which the one class doing so then does). Then you can invoke the counter in the mixin as just this.counter.

Upvotes: 1

Related Questions