How can I initialize a mixin's immutable data in Dart? How can I initialize a mixin's immutable data in Dart? dart dart

How can I initialize a mixin's immutable data in Dart?


You can change the declaration of your mixin to:

mixin Salt {  int get pitches;}

And then define the field inside the implementation class

class Meat with Salt {  final int pitches;  Meat(this.pitches);} 


By design it is not possible to declare a final member into a mixin because it is not possible to declare a constructor for initializing the final member, citing the docs:

However, in this proposal, a mixin may only be extracted from a class that has no declared constructors. This restriction avoids complications that arise due to the need to pass constructor parameters up the inheritance chain.

A compromise may be to declare a private member and implement only a getter.
_pinches is visible only inside the library, it is read-only for library users.

mixin Salt {  int _pinches;  get pinches => _pinches;}class Meat with Salt {  Meat(int pinches)  {   _pinches = pinches;  }}

Note: the above pattern, because of the visibility rules, works only if the mixin and the mixed classes reside in the same library.


Similar to attdona's suggestion, but a little bit closer to what you really wanted, you could do it like

mixin Salt {  int _pinches;  int get pinches => _pinches;  void initSalt(int pinches) {    assert(_pinches == null);    _pinches = pinches;  }}class Meat with Salt {  Meat(int pinches) {    initSalt(pinches);  }}

It's still not strictly final, but (so long as the mixin's in a different library so you can't change the private member directly) it's immutable at runtime. Not as good as if it could be properly final, but maybe close enough.