Methods

Methods are functions that provide behavior for an object.

Instance methods

Instance methods on objects can access instance variables and this.The distanceTo() method in the following sample is an example of aninstance method:

  1. import 'dart:math';
  2. class Point {
  3. num x, y;
  4. Point(this.x, this.y);
  5. num distanceTo(Point other) {
  6. var dx = x - other.x;
  7. var dy = y - other.y;
  8. return sqrt(dx * dx + dy * dy);
  9. }
  10. }

Getters and setters

Getters and setters are special methods that provide read and writeaccess to an object’s properties. Recall that each instance variable hasan implicit getter, plus a setter if appropriate. You can createadditional properties by implementing getters and setters, using theget and set keywords:

  1. class Rectangle {
  2. num left, top, width, height;
  3. Rectangle(this.left, this.top, this.width, this.height);
  4. // Define two calculated properties: right and bottom.
  5. num get right => left + width;
  6. set right(num value) => left = value - width;
  7. num get bottom => top + height;
  8. set bottom(num value) => top = value - height;
  9. }
  10. void main() {
  11. var rect = Rectangle(3, 4, 20, 15);
  12. assert(rect.left == 3);
  13. rect.right = 12;
  14. assert(rect.left == -8);
  15. }

With getters and setters, you can start with instance variables, laterwrapping them with methods, all without changing client code.

Note: Operators such as increment (++) work in the expected way, whether or not a getter is explicitly defined. To avoid any unexpected side effects, the operator calls the getter exactly once, saving its value in a temporary variable.

Abstract methods

Instance, getter, and setter methods can be abstract, defining aninterface but leaving its implementation up to other classes.Abstract methods can only exist in abstract classes.

To make a method abstract, use a semicolon (;) instead of a method body:

  1. abstract class Doer {
  2. // Define instance variables and methods...
  3. void doSomething(); // Define an abstract method.
  4. }
  5. class EffectiveDoer extends Doer {
  6. void doSomething() {
  7. // Provide an implementation, so the method is not abstract here...
  8. }
  9. }