Members
suggest changeA class can have members.
Instance variables can be declared with or without type annotations, and optionally initialized. Uninitialised members of a nullable type, or declared with var (type dynamic), are null. A non-nullable field must be initialized, marked late, or set by an initializing formal or initializer list.
class Foo {
var member1;
int? member2;
String member3 = "Hello world!";
}
Class variables are declared using the static keyword.
class Bar {
static var member4;
static String? member5;
static int member6 = 42;
}
If a method takes no arguments, is fast, returns a value, and doesn’t have visible side-effects, then a getter method can be used:
class Foo {
String get bar {
var result = 'bar';
// ...
return result;
}
}
Getters never take arguments, so the parentheses for the (empty) parameter list are omitted both for declaring getters, as above, and for calling them, like so:
main() {
var foo = new Foo();
print(foo.bar); // prints "bar"
}
There are also setter methods, which must take exactly one argument:
class Foo {
late String _bar;
String get bar => _bar;
set bar(String value) {
_bar = value;
}
}
The syntax for calling a setter is the same as variable assignment:
main() {
var foo = new Foo();
foo.bar = "this is calling a setter method";
}