Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable setter generation without using final?

Tags:

dart

For fun and to learn, I'm building a simple game engine with Dart. I have defined an abstract Game class. A Game has a Director director field which manages scene transitions. This class is also abstract. Each concrete game must implement its own concrete Game and Director classes, say MyGame and MyDirector.

I'm setting Game's director like this:

abstract class Game {
  Director director;

  Game() {
    director = createDirector();
  }

  Director createDirector();
}

MyGame (which inherits from Game) implements createDirector().

Using this approach Dart generates a setter for the director field so users of Game instances can change it like this game.director = something;. I don't want that to be possible. The usual way to solve this is to make the director field final, but I cannot do this because of how its assigned/created inside the Game constructor (and not the initialization list).

How can I disable the generation of the director setter in this situation?

like image 322
Rasmus Rønn Nielsen Avatar asked Oct 29 '25 22:10

Rasmus Rønn Nielsen


1 Answers

Making it final is what's recommended but indeed you won't be able to assign to it in the constructor.

Alternatively you can do what the style guide considers unadvisable, wrap a private field with a getter without a setter:

abstract class Game {
  var _director;
  get director => _director;
}
like image 187
mockinterface Avatar answered Oct 31 '25 11:10

mockinterface



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!