๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Dart Classes

A class is a plan for making objects. Each object made from a class holds its own stored values.

Fields on an object

A field is a stored value that belongs to an object. The constructor Dog(this.name, this.age) fills both fields when an object is made.

class Dog {
  String name;
  int age;
  Dog(this.name, this.age);
}

void main() {
  var rex = Dog('Rex', 4);
  print(rex.name);
  print(rex.age);
}

A method on a class

A method is a function that belongs to a class. describe reads the fields of its own object and prints them as one line.

class Dog {
  String name;
  int age;
  Dog(this.name, this.age);
  void describe() {
    print('$name is $age years old');
  }
}

void main() {
  var rex = Dog('Rex', 4);
  rex.describe();
}

Two objects from one class

One class can make many objects in a program. Each object keeps its own field values, so the two lines differ.

class Dog {
  String name;
  int age;
  Dog(this.name, this.age);
  void describe() {
    print('$name is $age years old');
  }
}

void main() {
  var rex = Dog('Rex', 4);
  var bella = Dog('Bella', 2);
  rex.describe();
  bella.describe();
}

A getter on a class

A getter is a value that a class computes from its fields. label joins the name and the age, and main reads it with no parentheses.

class Dog {
  String name;
  int age;
  Dog(this.name, this.age);
  String get label => '$name ($age)';
}

void main() {
  var rex = Dog('Rex', 4);
  print(rex.label);
}

Example

class Dog {
  String name;
  int age;
  Dog(this.name, this.age);
  void describe() {
    print('$name is $age years old');
  }

  String get label => '$name ($age)';
}

void main() {
  var rex = Dog('Rex', 4);
  var bella = Dog('Bella', 2);
  rex.describe();
  bella.describe();
  print(rex.label);
}

Key points

  • Use the class name with parentheses to make an object.
  • Use a dot to reach a field or a method of an object.
  • Each object keeps its own field values.
  • A getter has no parentheses when an object reads it.

In this example, the class Dog holds two fields, a constructor, a method, and a getter. The constructor fills the name and the age of each object. describe prints one line for Rex and one line for Bella. The getter label then builds a short text for Rex, and the last print shows it.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

Which line makes an object from the class Dog?