Everything is an object
In Dart, every value is an object, an instance of some class: numbers, strings, functions, even null. Classes are how you define your own kinds of objects, and Dart gives them a rich toolkit: several kinds of constructors, getters and setters that look like fields, operators you can define, and three ways to share code between classes (inheritance, interfaces and mixins). Flutter is built entirely from classes; every widget you write extends one.
Dart's object model resembles Java's and C#'s, with a few twists worth learning early. Privacy is per library (per file), not per class, and is marked by a leading underscore instead of a keyword. Every class automatically defines an interface. Mixins provide reuse without deep hierarchies. And since Dart 3, class modifiers let a library author say exactly how a class may be used by others.
A class from the ground up
class Money {
final int cents; // public, final
final String currency;
// A const constructor with initializing formals and an assert in the initializer list.
const Money(this.cents, this.currency) : assert(cents >= 0);
// A named constructor.
const Money.zero(this.currency) : cents = 0;
// A factory constructor can validate, compute, or return an existing object.
factory Money.parse(String text) {
final [amount, currency] = text.split(' ');
final parts = amount.split('.');
final whole = int.parse(parts[0]);
final fraction = parts.length > 1
? int.parse(parts[1].padRight(2, '0'))
: 0;
return Money(whole * 100 + fraction, currency);
}
// A getter: computed, called without parentheses.
bool get isZero => cents == 0;
// Operators are methods too.
Money operator +(Money other) {
if (other.currency != currency) {
throw ArgumentError('cannot add $currency and ${other.currency}');
}
return Money(cents + other.cents, currency);
}
// Value equality: two Money objects with the same contents are equal.
@override
bool operator ==(Object other) =>
other is Money && other.cents == cents && other.currency == currency;
@override
int get hashCode => Object.hash(cents, currency);
@override
String toString() =>
'${cents ~/ 100}.${(cents % 100).toString().padLeft(2, '0')} $currency';
}
class Wallet {
final _items = <Money>[]; // a private field: the name starts with _
void add(Money m) => _items.add(m);
int get count => _items.length;
}
void main() {
const fare = Money(250, 'KES');
final lunch = Money.parse('3.5 KES');
print(fare + lunch);
print(Money.zero('KES').isZero);
print(Money.parse('2.50 KES') == fare);
print({fare, Money(250, 'KES'), lunch}.length);
print(identical(const Money(250, 'KES'), fare));
// Cascades (..) call several members on the same object.
final wallet = Wallet()
..add(fare)
..add(lunch);
print(wallet.count);
}6.00 KES
true
true
2
true
2Walk through Money:
- Initializing formals.
Money(this.cents, this.currency)assigns parameters straight to fields; no constructor body is needed. - Initializer lists. After the colon, before the body, a constructor can assign
finalfields (cents = 0inMoney.zero) and checkasserts. Final fields must be set before the body runs, so this is where they are set when initializing formals are not enough. - Named constructors such as
Money.zerogive a class several ways to be created, each with a descriptive name; Dart has no constructor overloading. constconstructors allow compile-time constant instances when every field isfinal. Identical constant expressions produce one shared object, which is whyidentical(const Money(250, 'KES'), fare)istrue. Flutter usesconstwidgets heavily so that unchanged parts of the screen are not rebuilt.- Factory constructors do not have to create a new instance of exactly this class: they can parse, validate, return a cached object or a subclass.
Money.parseuses a list pattern,final [amount, currency] = ..., to take the split string apart; the lesson on patterns explains it. - Getters (
get isZero) are methods called without parentheses. Callers cannot tell a getter from a field, so you can switch between them without breaking anyone. - Operators such as
+and==are methods with special names. - Equality. By default,
==compares identity.Moneyoverrides==to compare contents, and must then overridehashCodeconsistently, here withObject.hash, or it will misbehave in sets and maps. With both, the set{fare, Money(250, 'KES'), lunch}has 2 elements. - Privacy.
_itemsstarts with an underscore, so it is visible only inside this library (this file). There is noprivatekeyword. - Cascades.
Wallet()..add(fare)..add(lunch)calls two methods on the same new object and evaluates to that object. Cascades are common for configuring objects in one expression.
Setters and static members
A setter runs code when a property is assigned, and a static member belongs to the class rather than to any instance:
class Thermostat {
static const maxTarget = 30;
static int instances = 0;
double _target = 20;
Thermostat() {
instances++;
}
double get target => _target;
set target(double value) => _target = value.clamp(5, maxTarget).toDouble();
}
void main() {
final t = Thermostat()..target = 42;
Thermostat();
print('${t.target} ${Thermostat.instances}'); // prints: 30.0 2
}Callers write t.target = 42 as if target were a field, and the setter clamps the value into range. The pair of a private field and a public getter (with or without a setter) is the standard way to expose state while keeping control of it. Static members are reached through the class name, Thermostat.instances. Use them sparingly: a mutable static is global state, with all the testing headaches that brings.
Primary constructors and concise constructors (Dart 3.13)
Simple data classes spend many lines declaring fields and then a constructor that assigns them. Dart 3.13 added primary constructors, which declare both in the class header, and a concise syntax for constructors in the body:
// Primary constructors (Dart 3.13): fields and constructor in the class header.
class Point(final int x, final int y) {
int get manhattan => x.abs() + y.abs();
@override
String toString() => '($x, $y)';
}
// `class const` makes the primary constructor a const constructor.
class const Size(final double width, final double height);
// Concise constructor syntax (Dart 3.13): `new` and `factory` instead of the class name.
class Temperature {
final double celsius;
new(this.celsius);
new freezing() : celsius = 0;
factory fromFahrenheit(double f) => Temperature((f - 32) * 5 / 9);
}
void main() {
final p = Point(3, -4);
print('$p ${p.manhattan}');
const a4 = Size(210, 297);
print('${a4.width} x ${a4.height}');
print(Temperature.fromFahrenheit(212).celsius);
print(Temperature.freezing().celsius);
}(3, -4) 7
210.0 x 297.0
100.0
0.0class Point(final int x, final int y) declares two final fields and a constructor that takes them, in one line; a class body can still follow. class const Size(...) makes the primary constructor const. Inside a class body, a constructor can now be introduced with new or factory instead of repeating the class name: new freezing() declares the named constructor Temperature.freezing. These features change how a class is written, not how it behaves. Because they are new, most existing code and tutorials use the classic form, so you need to read both; a package must have an SDK constraint of at least 3.13 to use them.
Inheritance, interfaces and mixins
abstract class Shape {
String get name;
double area();
// A concrete method, inherited by every subclass.
String describe() => '$name with area ${area().toStringAsFixed(1)}';
}
class Rectangle extends Shape {
final double width, height;
Rectangle(this.width, this.height);
@override
String get name => 'rectangle';
@override
double area() => width * height;
}
class Square extends Rectangle {
Square(double side) : super(side, side);
@override
String get name => 'square';
}
// A mixin bundles members that several unrelated classes can reuse with `with`.
mixin Labelled {
String get label;
String tag() => '[$label]';
}
mixin Logged {
final log = <String>[];
void record(String event) => log.add(event);
}
class Triangle extends Shape with Labelled, Logged {
final double base, height;
Triangle(this.base, this.height) {
record('created');
}
@override
String get name => 'triangle';
@override
String get label => 'T-$base';
@override
double area() => base * height / 2;
}
// Every class also defines an interface; `implements` promises its members
// without inheriting any code.
class Circle implements Shape {
final double r;
Circle(this.r);
@override
String get name => 'circle';
@override
double area() => 3.14159 * r * r;
@override
String describe() => 'a circle of radius $r';
}
void main() {
final shapes = <Shape>[Rectangle(2, 3), Square(4), Triangle(6, 2), Circle(1)];
for (final s in shapes) {
print(s.describe());
}
final t = shapes[2] as Triangle;
print('${t.tag()} ${t.log}');
print(shapes.whereType<Rectangle>().length);
}rectangle with area 6.0
square with area 16.0
triangle with area 6.0
a circle of radius 1.0
[T-6.0] [created]
2abstract class Shapecannot be instantiated. It declares abstract members (name,area) that subclasses must implement, and a concretedescribethat they inherit.extendscreates a subclass.Squarepasses its side twice toRectangle's constructor withsuper(side, side), and overridesname. The@overrideannotation is optional, but the recommended lints require it, so a typo that fails to override anything is caught.- Mixins (
mixin Labelled,mixin Logged) are bundles of members that a class adds withwith. A mixin can declare abstract members (label) that the class must provide, and can carry state (log). Mixins give the reuse of multiple inheritance while keeping a single, linear superclass chain:Triangle's chain isShape, thenLabelled, thenLogged, so a member defined in a later mixin overrides an earlier one with the same name. - Implicit interfaces. Every class defines an interface made of its public members.
Circle implements Shapepromises all of them and inherits nothing, so it must implementdescribeitself. Dart has no separateinterfacedeclaration for this; an abstract class serves.
The as Triangle cast and whereType let the program reach type-specific members from a list typed with the general Shape.
Class modifiers (Dart 3.0)
Since Dart 3.0, a library can restrict how other libraries use its classes:
| Modifier | Other libraries may | Typical use |
|---|---|---|
| (none) | construct, extend and implement it | ordinary classes |
abstract | extend and implement, not construct | partial implementations |
base | extend, but not implement | classes whose private invariants must be inherited |
interface | implement, but not extend | pure contracts |
final | neither extend nor implement | closed implementation classes |
sealed | neither; all subtypes live in the same library, so switch can be exhaustive | closed families of types (next lesson) |
mixin class | use it as a class or as a mixin | code meant for both roles |
Inside its own library, a class can always be extended and implemented. These modifiers matter most to package authors, who need to change their classes without breaking users.
Extension methods and extension types
// An extension adds methods to a type you did not write.
extension Initials on String {
String get initials =>
split(' ')
.where((w) => w.isNotEmpty)
.map((w) => w[0].toUpperCase())
.join();
}
extension Stats on Iterable<num> {
double get mean => isEmpty ? 0 : fold<num>(0, (a, b) => a + b) / length;
}
// An extension type (Dart 3.3) gives an existing representation a new, distinct
// static type, with no wrapper object at run time.
extension type const UserId(int value) {
bool get isSystem => value < 1000;
}
extension type OrderId(int value) {}
void greet(UserId id) =>
print('user ${id.value}, system account: ${id.isSystem}');
void main() {
print('chinua achebe'.initials);
print(' ngũgĩ wa thiong\'o '.initials);
print([3, 4, 8].mean);
print(<int>[].mean);
const root = UserId(7);
greet(root);
greet(UserId(52044));
final order = OrderId(52044);
// greet(order); // compile error: an OrderId is not a UserId
print(order.value == 52044);
}CA
NWT
5.0
0.0
user 7, system account: true
user 52044, system account: false
trueAn extension (since Dart 2.7) adds methods, getters and operators to an existing type, even one from the SDK like String, without subclassing it. 'chinua achebe'.initials reads as if String had always had that getter. extension Stats on Iterable<num> adds mean to every list, set and iterable of numbers. Extension members are resolved statically, by the static type of the expression: they are syntactic sugar for calling a function, so they cannot be overridden, and they do not work on a value whose static type is dynamic.
An extension type (since Dart 3.3) goes the other way: it wraps an existing representation, here an int, in a new static type, with no wrapper object at run time. UserId and OrderId are both just integers in memory, but the compiler keeps them apart: passing an OrderId to greet fails with The argument type 'OrderId' can't be assigned to the parameter type 'UserId'. That turns a whole class of mix-ups into compile errors at zero cost, and extension types are also how Dart wraps JavaScript objects in its web interop. Their limit is that the protection is static only: at run time, UserId(5) is int is true, so an is check cannot tell the types apart.
Where these ideas come from
Dart's object model shows its ancestry. The idea of a mixin as a reusable "slice" of a class, applied in a fixed order, goes back to Lisp and Smalltalk systems of the 1980s and was formalized in the 1990 paper Mixin-based Inheritance by Gilad Bracha and William Cook; Bracha later worked on Dart's original specification. Implicit interfaces and getters that look like fields come from the same Smalltalk tradition, in which everything is a message sent to an object. Other details came from practice: the new keyword, once required before every constructor call, became optional in Dart 2.0 because Flutter code, which builds deep trees of objects, read far better without it. And the class modifiers of Dart 3.0 were added because package authors needed a way to change their classes without breaking code that extended them in unexpected ways.
Designing classes the Dart way
Experienced Dart developers, especially in Flutter, favour immutable classes: all fields final, a const constructor where possible, and a copyWith method that returns a modified copy instead of changing the original. Immutable objects can be shared freely, compared by value, and used safely as map keys, and Flutter's rebuild model works best when state objects do not change behind its back. The @immutable annotation from the Dart team's meta package makes the analyzer warn if a subclass adds a mutable field.
Writing ==, hashCode, toString, copyWith and JSON conversion by hand for every data class is tedious and error-prone, so many teams use code generation: packages such as json_serializable and freezed, run by build_runner, generate those members from a short annotated declaration. For small, local groupings of values, the records of the next lesson often replace a class altogether, with value equality built in.
Beyond that, the usual object-oriented advice applies with a Dart accent. Prefer composition and mixins to deep inheritance hierarchies. Keep classes small, and do not write a class just to hold static functions: top-level functions are first-class citizens. Mark classes final or interface in packages when you do not intend them to be extended, so that you can change them later without breaking anyone.
Common misconceptions
Misconception
"An underscore makes a member private to its class." It makes it private to its library, normally the file. Other classes in the same file can see it. Split code into files if you need tighter boundaries.
Misconception
"I can override == and leave hashCode alone." Equal objects must have equal hash codes, or sets and maps will treat them as different keys. Override both together; Object.hash makes hashCode a one-liner.
Misconception
"Extension methods are dynamic, like JavaScript's prototype patching." They are resolved at compile time from the static type. Assign a String to a dynamic or Object variable and its extension getters disappear.
Misconception
"Mixins are just multiple inheritance." They are applied in a fixed order, forming a single chain, so there is never ambiguity about which member wins: the last one applied.
Exercises
1. Classes, mixins and extensions
StretchComputationalP has a const constructor and no == override. Q is the same but overrides == and hashCode to compare x. What does this line print?
print('${{P(1), P(1)}.length} ${{Q(1), Q(1)}.length} ${{const P(1), const P(1)}.length}');
2. Classes, mixins and extensions
CoreComputationalWhat does this program print?
mixin A { String hi() => 'A'; }
mixin B { String hi() => 'B'; }
class Base { String hi() => 'Base'; }
class C extends Base with A, B {}
class D extends Base with B, A {}
void main() => print('${C().hi()}${D().hi()}');
3. Classes, mixins and extensions
Warm-upComputationalWhat does this print?
final list = [3, 1, 2]
..sort()
..add(0);
print(list);
4. Classes, mixins and extensions
CoreHumanShape is an abstract class with abstract name and area(), and a concrete method describe(). A class declares class Circle implements Shape. Which members must Circle define itself?
5. Classes, mixins and extensions
CoreComputationalAn extension adds String get shout to String. What happens with dynamic d = 'hey'; print(d.shout);?
6. Classes, mixins and extensions
CoreHumanYou publish a package with a class Cache. Other packages should be able to write their own implementations of its interface, but must not inherit its implementation code. Which modifier fits?
7. Classes, mixins and extensions
CoreComputationalWhat does this program print?
class Ticket {
static int issued = 0;
final int number;
Ticket() : number = ++issued;
}
void main() {
final a = Ticket();
final b = Ticket();
final c = Ticket();
print(a.number + b.number * 10 + c.number * 100);
}