CorayThan
CorayThan

Reputation: 17845

Override getter functionality in Dart?

I want to declare a field in dart, and only override the functionality of the getter, but I'm not sure how / if that is possible.

class Pony {
  String ponyGreeting;
  String ponyName;
  Pony(this.ponyGreeting, this.ponyName);

  String get ponyGreeting => "$ponyGreeting I'm $ponyName!";
}

That causes an error, though, because I've already defined "ponyGreeting". I can't just get rid of the field ponyGreeting, because I want to set it using the constructor, and if I made a setter I would have to set that value somewhere, and I don't really want a superfluous property.

Upvotes: 3

Views: 4481

Answers (1)

Pixel Elephant
Pixel Elephant

Reputation: 21403

You can use a private variable alongside the getter:

class Pony {
  String _ponyGreeting;
  String ponyName;
  Pony(this._ponyGreeting, this.ponyName);

  String get ponyGreeting => "$_ponyGreeting I'm $ponyName!";
}

Upvotes: 9

Related Questions