TExcelTAD
Home › Dart › Dart Classes

Dart Classes

Dart is an object-oriented language: every value is an instance of a class, and every class (except Null) ultimately extends Object. A class bundles data (fields) with behaviour (methods) and acts as a blueprint for creating objects (instances).

Defining a class

dart · try it yourself
class Product {
  // Fields (instance variables)
  final String name;
  final int priceCents;
  int quantity;

  // Constructor using initializing formals
  Product(this.name, this.priceCents, [this.quantity = 1]);

  // Method
  int totalCents() => priceCents * quantity;

  // Method with side effects
  void restock(int amount) {
    quantity += amount;
  }
}

void main() {
  final pen = Product('Pen', 150, 4);  // `new` is optional and omitted
  final lamp = Product('Lamp', 2500);

  print(pen.name);
  print(pen.totalCents());
  lamp.restock(2);
  print('${lamp.name} x${lamp.quantity} = ${lamp.totalCents()}');
}
Pen
600
Lamp x3 = 7500

this.name in the parameter list is an initializing formal: it assigns the argument straight to the field. It's the idiomatic way to write simple constructors — see Constructors for all the options.

Fields and null safety

Every non-nullable field must be initialised before the constructor body runs — by a default value, an initializing formal, or an initializer list. Otherwise the class won't compile:

dart · try it yourself
class User {
  String name;
  int age;
  User(this.name);
}

void main() {
  print(User('Vy').name);
}
example.dart:3:7: Error: Field 'age' should be initialized because its type 'int' doesn't allow null.
  int age;
      ^^^
Error: AOT compilation failed
Bad state: Generating AOT kernel dill failed!

Fixes: give age a default (int age = 0;), make it nullable (int? age;), mark it late, or initialise it in the constructor.

this, toString, and ==

this refers to the current object. You rarely need it except to disambiguate a parameter from a field. Two methods every class inherits from Object are worth overriding:

dart · try it yourself
class Point {
  final int x;
  final int y;
  const Point(this.x, this.y);

  Point operator +(Point other) => Point(x + other.x, y + other.y);

  int squaredDistanceTo(Point other) {
    final dx = x - other.x;
    final dy = y - other.y;
    return dx * dx + dy * dy;
  }

  @override
  String toString() => 'Point($x, $y)';

  @override
  bool operator ==(Object other) => other is Point && other.x == x && other.y == y;

  @override
  int get hashCode => Object.hash(x, y);
}

void main() {
  const a = Point(1, 2);
  const b = Point(3, 4);
  print(a + b);
  print(a == Point(1, 2));
  print({a, Point(1, 2), b}.length);
  print(a.squaredDistanceTo(b));
}
Point(4, 6)
true
2
8

Without the ==/hashCode overrides, two separately created Point(1, 2) objects would be unequal (identity comparison). Dart also lets you define operators like +, -, [] and < on your own classes.

Tip: If all you need is a bundle of values with value equality, a record such as (x: 1, y: 2) gives you ==, hashCode and toString for free.

Static members

static fields and methods belong to the class, not to instances. Use them for constants, counters and factory helpers:

dart · try it yourself
class Ticket {
  static int _issued = 0;
  static const prefix = 'TK';

  final String code;

  Ticket() : code = '$prefix-${++_issued}';

  static int get issuedCount => _issued;
}

void main() {
  final t1 = Ticket();
  final t2 = Ticket();
  print(t1.code);
  print(t2.code);
  print(Ticket.issuedCount);
}
TK-1
TK-2
2

Objects are references

Variables hold references to objects. Passing an object to a function or assigning it to another variable doesn't copy it:

dart · try it yourself
class Box {
  int value;
  Box(this.value);
}

void bump(Box b) => b.value++;

void main() {
  final a = Box(1);
  final b = a;
  bump(b);
  print(a.value);
  print(identical(a, b));
}
2
true

Class members at a glance

Member Example
Instance field int quantity;
Final field final String name;
Static field static int count = 0;
Constructor Product(this.name);
Method void restock(int n) { … }
Getter / setter int get total => …; set total(int v) { … }
Operator Point operator +(Point o) => …;
Static method static Product parse(String s) { … }

Test yourself

What does Product(this.name) do?

  1. Calls a method named name
  2. Assigns the argument directly to the name field
  3. Creates a static field
  4. Declares a getter

Which two members should you override together to give a class value equality?

  1. toString and ==
  2. == and hashCode
  3. hashCode and toString
  4. compareTo and ==

A static field belongs to…

  1. Each instance separately
  2. The class itself, shared by all instances
  3. The library only
  4. The first instance created