Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am programming in Flutter using Dart 2.1.0, and come across this situation:

mixin Salt {
  final int pinches;  // Immutable, and I want to delay initialization.

  // Cannot declare constructors for mixin
}

class Meat with Salt {
  Meat(int pinches) ... // How to initialize it?
}

Salt has no constructor, so I cannot use initializer list. pinches is final, so I cannot set it in Meat's constructor.

I don't want to make Salt a class because Meat may need to extend from something else.

And I want to keep pinches immutable.

Any way to do it? Thanks in advance.

like image 589
Nick Lee Avatar asked Jan 13 '19 07:01

Nick Lee


People also ask

How do you initialize a Dart function?

Either declare the function as static in your class or move it outside the class altogether. If the field isn't final (which for best practice, it should be, unless the field has to mutate), you can initialize it using a regular non-static method in the constructor body.

What is immutable object in Dart?

Immutable data constructs are those that cannot be mutated (altered) after they've been initialized. The Dart language is full of these. In fact, most basic variable types operate this way. Once created, strings, numbers, and boolean values cannot be mutated.

Which of the following type of objects are completely immutable in Dart?

Immutable Data in Dart: Once made, strings, numbers, and boolean values can't be mutated. A string variable doesn't contain string data, itself.

Is list immutable in Dart?

A native Dart list is mutable, meaning you can change its items: var list = [1, 2];


2 Answers

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);
} 
like image 118
Rémi Rousselet Avatar answered Oct 23 '22 09:10

Rémi Rousselet


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.

like image 6
attdona Avatar answered Oct 23 '22 07:10

attdona