Sub topic 1
Classes and objects
A class describes the shape and behavior of a kind of value. An object is one concrete value built from that description. This chapter covers how Dart classes and objects work at runtime: how you create objects, where their state lives, and how variables refer to them. Later chapters cover constructors, inheritance, and mixins in detail.
Prerequisites
This chapter assumes you already know:
- Basic Dart syntax: variables, types, functions, and control flow.
- Null safety basics: the difference between
StringandString?. - The general idea of objects and methods from another language.
What a class is
A class bundles data (fields) with functions that work on that data (methods). Here is a small one.
class Counter {
int value = 0;
void increment() {
value++;
}
}
void main() {
final a = Counter();
a.increment();
a.increment();
print(a.value); // 2
}Counter() creates a new object, called an instance of Counter. Dart has no new keyword requirement. Writing new Counter() is legal but unnecessary, and style guides recommend leaving it out.
Inside a method you refer to fields by their bare name. value++ works because Dart resolves value to the field of the current object. You only write this.value when a local name shadows the field.
Everything is an object
In Dart every value is an object, including numbers, booleans, functions, and null. Every class extends Object unless you say otherwise, and Object supplies a few members every instance has:
toString()returns a text description.==andhashCodedefine equality.runtimeTypereturns the object's actual type.
The next example shows the defaults.
class Box {
int size = 1;
}
void main() {
final box = Box();
print(box); // Instance of 'Box'
print(box.runtimeType); // Box
print(box is Box); // true
print(box is Object); // true
print(42.runtimeType); // int
}The default toString() is rarely useful. Override it on any class you print or log.
class Temperature {
double degrees = 20;
@override
String toString() => 'Temperature($degrees C)';
}
void main() {
print(Temperature()); // Temperature(20.0 C)
}Objects are references
A variable of a class type holds a reference to an object, not the object itself. Assigning one variable to another copies the reference. Both variables then point at the same object.
class Box {
int size = 1;
}
void main() {
final a = Box();
final b = a; // same object as a
final c = Box(); // a new, separate object
b.size = 5;
print(a.size); // 5
print(a == b); // true
print(a == c); // false
print(identical(a, c)); // false
}The default == compares identity: two references are equal only if they point to the same object. Two Box objects with the same size are still not equal unless you override == and hashCode yourself.
final does not freeze the object
final fixes which object a variable refers to. It does not stop the object's own fields from changing. In the example above, final b = a; still lets you write b.size = 5. What you cannot do is write b = Box();. To make an object's state unchangeable, declare its fields final. A later chapter covers that pattern.
Fields start with a default
Dart's null safety rules decide what a field holds before you assign it.
| Declaration | Starting value | Notes |
|---|---|---|
| `String? nickname;` | `null` | Nullable fields default to `null`. |
| `int visits = 0;` | `0` | Non-nullable fields need an initial value. |
| `late String token;` | none | Reading before assignment throws `LateInitializationError`. |
A non-nullable field with no initial value and no constructor assignment is a compile-time error. That rule is why the late modifier exists. It promises the compiler that you will assign the field before the first read.
class Session {
String? nickname;
int visits = 0;
late String token;
}
void main() {
final s = Session();
print(s.nickname); // null
print(s.visits); // 0
s.token = 'abc123';
print(s.token); // abc123
}Working with an object
Member access and null-aware access
You reach fields and methods with a dot. If the variable might be null, use ?. so the access is skipped when the variable is null.
class Counter {
int value = 0;
void increment() => value++;
}
void main() {
Counter? maybe;
maybe?.increment(); // does nothing, no error
print(maybe?.value); // null
maybe = Counter();
maybe.increment(); // promoted to non-null after assignment
print(maybe.value); // 1
}Cascades
A cascade (..) calls several members on the same object and then evaluates to that object. It saves you from repeating a variable name.
class Counter {
int value = 0;
void increment() => value++;
}
void main() {
final c = Counter()
..increment()
..increment()
..value += 10;
print(c.value); // 12
}Without the cascade, Counter().increment() would give you the result of increment(), which is void, not the counter. The cascade keeps the receiver, so c holds the Counter.
Type tests and promotion
Use is to check an object's type. When the check succeeds, Dart treats the variable as that type inside the branch.
class Cat {
void meow() => print('meow');
}
void main() {
final Object pet = Cat();
if (pet is Cat) {
pet.meow(); // pet is promoted to Cat here
}
}Use runtimeType for diagnostics only. Comparing a.runtimeType == b.runtimeType is stricter than is, because it fails for subclasses. It is also easy to get wrong.
Common errors
- Forgetting parentheses.
final a = Counter;stores the class itself as aTypevalue and does not create an object. WriteCounter(). - Expecting copies.
final b = a;does not copy the object. If you need an independent object, create a new one and copy the fields yourself. - Expecting value equality. Two objects with the same field values are not
==by default. Override==andhashCodetogether, or the object will misbehave as aMapkey orSetelement. - Reading a
latefield too soon. The error appears at runtime, often far from the cause. - Mutating through
final. Afinalvariable can still refer to an object whose fields change.
Summary of the model
A class is a template. Calling it, as in Box(), creates an object with its own copy of the instance fields. Variables hold references, so several variables can share one object. Equality defaults to identity. Null safety decides whether a field starts as null, needs an initial value, or must be marked late. The next chapters build on this by looking at fields, methods, getters, and setters in detail.
Exercise
Given the class class Box { int size = 1; }, what do the last two lines print?
final a = Box();
final b = a;
b.size = 9;
print(a.size);
print(a == Box());
Show answer
The first line prints 9, because b and a refer to the same object, so the change made through b is visible through a. The second line prints false, because the default == compares identity and Box() creates a new, different object, even though its size would be 1.
Exercise
A class declares late String token;. A method reads token before any code has assigned it. When is the problem reported, and what would you change if the value is known at construction time?
Show answer
It is reported at runtime, when the read happens, as a LateInitializationError. The compiler does not catch it. If the value is known when the object is created, drop late and give the field an initial value, or initialize it in the constructor, so the compiler can check it for you.