Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 61 ยท Classes and Object-Oriented Dart

Classes and Objects

Learn Dart classes and objects: declaring fields and methods, creating instances without new, the this keyword, toString, cascades, and library-level privacy with underscores.

So far you have worked with values that Dart provides: numbers, strings, lists, maps. Real programs also need their own kinds of values: a User, an Invoice, a Point on a canvas. A class is a blueprint that describes what such a value remembers (its fields) and what it can do (its methods). An object, also called an instance, is one concrete value built from the blueprint.

Dart is a thoroughly object-oriented language: even numbers, booleans and functions are objects. This lesson starts the object-oriented chapter with the basics: declaring a class, making objects, using this, and controlling visibility with the underscore. Constructors, inheritance and mixins follow in later lessons. The Dart code is read-only; TypeScript stand-ins let you run the matching ideas.

Declaring a class

A class has a name (written in UpperCamelCase) and a body with its members:

DART
class Counter {
  int count = 0;                 // a field with a default value

  void increment() {             // a method
    count = count + 1;
  }

  int doubled() => count * 2;    // a method with an arrow body
}

void main() {
  var counter = Counter();       // create an instance
  counter.increment();
  counter.increment();
  print(counter.count);          // 2
  print(counter.doubled());      // 4
}

Things to notice:

  • Counter() creates an object. Dart has an optional new keyword, but nobody writes it any more.
  • Members are reached with the dot: counter.count, counter.increment().
  • Inside a method you can use the field name directly (count). Dart finds it because the method belongs to the class.
  • Every object has its own copy of the fields. Two counters never share a count.
flowchart TD
    C["class Counter<br/>count, increment(), doubled()"] --> A["object a<br/>count = 2"]
    C --> B["object b<br/>count = 1"]

One class, many objects: each instance carries its own field values.

TypeScript A first class (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Fields: instance variables

Fields are variables that belong to an object. Their types follow the rules from earlier lessons: a field must be initialized, nullable, or marked late.

DART
class Product {
  String name = 'unnamed';       // has a default
  double price = 0;              // int literal fits a double field
  String? description;           // nullable: starts as null
  late final DateTime created;   // assigned later, exactly once
  final int id = 1;              // cannot be reassigned after creation
}

A final field can be set once (here or in a constructor); a non-final field can change. Prefer final wherever you can, because objects that never change are easier to reason about. Dart generates an implicit getter for every field, and a setter for every non-final one, so product.price = 9.5 and print(product.name) look like plain field access. A later lesson, Getters, Setters and Properties, shows how to replace them with your own code without changing how callers use the class.

For now, the fields in these examples are set with their defaults or by assigning after creation. Writing Product() and then filling in every field is clumsy, and Constructors show the usual solution: pass the values in when the object is created. You will occasionally see the short form Point(this.x, this.y);, which declares a constructor that assigns both fields.

Methods and the this keyword

A method is a function that lives in a class. Inside it, this refers to the object the method was called on. You rarely need to write it: Dart uses this automatically when a name matches a field. The exception is a name clash between a parameter and a field. Then the bare name means the parameter, and this.name means the field:

DART
class Account {
  double balance = 0;

  void deposit(double amount) {
    balance += amount;               // field, no clash
  }

  void setBalance(double balance) {
    this.balance = balance;          // this. picks the field, the bare name is the parameter
  }

  Account copyWithBonus(double bonus) {
    var copy = Account();
    copy.balance = balance + bonus;
    return copy;
  }
}

void main() {
  var a = Account();
  a.deposit(50);
  a.setBalance(80);
  var b = a.copyWithBonus(5);
  print(a.balance);   // 80.0
  print(b.balance);   // 85.0
}

The official style guide says to use this. only to avoid a clash (or in a constructor's initializing formal). Methods can call other methods of the same object by name, and they can return this to allow chaining.

Callable objects

If a class defines a method named call, you can invoke an instance as if it were a function. That is how a small object that carries configuration can still be passed wherever a function is expected:

DART
class Multiplier {
  final int factor;
  Multiplier(this.factor);

  int call(int value) => value * factor;
}

void main() {
  var triple = Multiplier(3);
  print(triple(5));                       // 15
  print([1, 2, 3].map(triple).toList());  // [3, 6, 9]
}

Printing objects: toString

Printing an instance of a plain class shows something unhelpful like Instance of 'Counter'. Every class inherits a toString() method from Object, and you can override it with your own text. The @override annotation tells the analyzer you did this on purpose. Interpolation and print both call toString():

DART
class Point {
  int x = 0;
  int y = 0;

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

void main() {
  var p = Point();
  p.x = 3;
  print(p);                  // Point(3, 0)
  print('Position: $p');     // Position: Point(3, 0)
}

Cascades: several operations on one object

The cascade operator .. calls a member on an object and then discards the result, returning the object itself. It saves you from repeating the variable name:

DART
void main() {
  var p = Point()
    ..x = 3
    ..y = 4;
  print(p);   // Point(3, 4)
}

This is equivalent to var p = Point(); p.x = 3; p.y = 4;. Use ?.. when the target may be null. You will see cascades often when configuring objects.

TypeScript Methods, this and toString (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Privacy with the underscore

Dart has no private or public keywords. Instead, a name that starts with an underscore is private. The twist is the scope: privacy is per library, and in the simplest case a library is a single .dart file. It is not per class.

DART
class BankAccount {
  double _balance = 0;           // private to this library (file)

  double get balance => _balance;   // public read-only view

  void deposit(double amount) {
    if (amount <= 0) {
      throw ArgumentError('Amount must be positive');
    }
    _balance += amount;
  }

  void _audit() {                // a private method
    print('Balance is $_balance');
  }

  void report() => _audit();
}

Code in another file that imports this class cannot write account._balance or call account._audit(); the compiler reports an error. But other code in the same file, including other classes, can. So the rule is: the underscore hides the member from other libraries, not from other classes in the same file.

flowchart LR
    subgraph L["bank_account.dart (one library)"]
        A["BankAccount<br/>_balance, _audit()"]
        B["any other class here<br/>can use _balance"]
    end
    O["main.dart (another library)"] -.->|"cannot see _balance"| A
    O -->|"can use deposit(), balance"| A

The underscore marks library-private members: visible inside the file, hidden outside.

The practical benefit is encapsulation. By keeping _balance private and exposing only deposit and a getter, the class controls how its state changes, so a balance can never be set to a negative number from outside. Private names are not part of the class's public contract, so you may rename them freely without breaking anyone.

One last note: an underscore also hides top-level functions, variables and even whole classes (class _Helper {}) from other libraries.

TypeScript Encapsulation (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which line creates an instance of Counter in modern Dart?

    Calling the class name like a function creates an instance. The new keyword is allowed but optional and rarely written.
  2. 2. When must you write this. inside a method?

    Dart finds fields by name automatically. You need this. only to tell a field apart from a parameter or local variable of the same name.
  3. 3. What does a leading underscore in _balance mean?

    Dart privacy is library-level. Other code in the same file can still use _balance, but code in other libraries cannot.
  4. 4. What does Point()..x = 3..y = 4 evaluate to?

    A cascade performs each operation on the object and then yields the object, so the whole expression is the configured Point.

Summary

  • A class is a blueprint; Counter() creates an object that has its own copy of every field.
  • Fields hold state, methods hold behavior, and the dot reaches both; final fields cannot be reassigned.
  • this is implicit, and needed only to separate a field from a same-named parameter.
  • Override toString() so objects print readably; use .. cascades to configure an object in one expression.
  • A leading underscore makes a member private to its library, hiding it from other files but not from other code in the same file.

Next, learn the right way to initialize objects in Constructors.