What is the correct syntax for get/set properties in Dart and how can I memorize the property syntax?

Viewed 84

I find myself trying a couple of things before looking at the documentation about how to write a get/set property in Dart. I go

get int val => _val;
int val get => _val
val set(v) => _val = v;

and it does not make sense what the syntax should be. Is there an easy to remember rule-of-thumb for property syntax?

1 Answers

Imagine you were writing functions instead of properties. It makes sense to start those functions with the words "get" and "set".

void setVal(int v) => _val = v;
int getVal() => _val;

Now separate the "get" and "set" words, make it compile by removing void for set and () for get, and you have properties!

set val(int v) => _val = v;
int get val => _val;
Related