dart Classes Members


Example

A class can have members.

Instance variables can be declared with/without type annotations, and optionally initialized. Uninitialised members have the value of null, unless set to another value by the constructor.

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;
    // ...
    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 {
  String _bar;

  String get bar => _bar;

  void 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";
}