Dart Classes & Objects
Dart is an object-oriented language: you model things in your program as classes, and create objects (instances) from them. In Flutter, every widget is a class, so understanding classes is essential before building UIs.
Defining a class
A class groups fields (data) and methods (behaviour). You create an object by calling the class's constructor — the new keyword is optional and normally omitted.
class Dog {
String name;
int age;
Dog(this.name, this.age);
void bark() {
print('$name says woof!');
}
}
void main() {
var rex = Dog('Rex', 3);
var milo = Dog('Milo', 5);
rex.bark();
milo.bark();
print('${rex.name} is ${rex.age}');
rex.age = 4;
print('${rex.name} is now ${rex.age}');
}Rex says woof!
Milo says woof!
Rex is 3
Rex is now 4
Dog(this.name, this.age) is a constructor that assigns its arguments straight to the fields. The next lesson covers constructors in depth.
Immutable classes with final fields
In Flutter you'll mostly write immutable classes: their fields are final, and to "change" something you create a new object. Immutable objects are easier to reason about and safe to share.
class Product {
final String name;
final double price;
const Product(this.name, this.price);
Product copyWith({String? name, double? price}) =>
Product(name ?? this.name, price ?? this.price);
@override
String toString() => 'Product($name, $price)';
}
void main() {
const tea = Product('Tea', 2.5);
final bigTea = tea.copyWith(price: 3.0);
print(tea);
print(bigTea);
}Product(Tea, 2.5)
Product(Tea, 3.0)
The copyWith pattern is very common in Flutter (for example ThemeData.copyWith). Overriding toString controls how an object is printed — the @override annotation tells the compiler you are intentionally replacing an inherited method.
Getters, setters and private members
A getter looks like a field but computes its value. A setter runs code when you assign. Names starting with _ are private to the file (library), which is how Dart hides implementation details — there is no private keyword.
class BankAccount {
final String owner;
double _balance = 0;
BankAccount(this.owner);
double get balance => _balance;
bool get isEmpty => _balance == 0;
set deposit(double amount) {
if (amount <= 0) {
print('Ignored invalid deposit');
return;
}
_balance += amount;
}
}
void main() {
var acc = BankAccount('Mai');
print(acc.isEmpty);
acc.deposit = 50;
acc.deposit = -10;
print('${acc.owner}: ${acc.balance}');
}true
Ignored invalid deposit
Mai: 50.0
Static members
static fields and methods belong to the class itself, not to any particular object. Use them for constants and helper functions.
class Temperature {
static const freezingC = 0;
static int created = 0;
final double celsius;
Temperature(this.celsius) {
created++;
}
static double toFahrenheit(double c) => c * 9 / 5 + 32;
}
void main() {
Temperature(20);
Temperature(30);
print(Temperature.created);
print(Temperature.freezingC);
print(Temperature.toFahrenheit(100));
}2
0
212.0
Object equality
By default, == checks whether two variables refer to the same object. To compare by value, override == and hashCode together:
class Point {
final int x, y;
const Point(this.x, this.y);
@override
bool operator ==(Object other) =>
other is Point && other.x == x && other.y == y;
@override
int get hashCode => Object.hash(x, y);
}
class Plain {
final int v;
Plain(this.v);
}
void main() {
print(Point(1, 2) == Point(1, 2));
print(Plain(1) == Plain(1));
print({Point(1, 2), Point(1, 2)}.length);
}true
false
1
Tip: Writing
==,hashCode,toStringandcopyWithby hand gets tedious. Many Flutter projects generate them with packages such asfreezedorequatable. Dart records also have value equality for free.
Class vocabulary
| Term | Meaning |
|---|---|
| Class | A blueprint (class Dog { ... }) |
| Object / instance | A value created from a class (Dog('Rex', 3)) |
| Field | A variable belonging to an object |
| Method | A function belonging to an object |
| Getter / setter | Computed property read / write |
this |
The current object |
static |
Belongs to the class, not to instances |
Test yourself
How do you make a field private in Dart?
- Use the
privatekeyword - Start its name with an underscore
- Mark it
final - Declare it
static
Which member is called with Temperature.toFahrenheit(10) rather than on an instance?
- A getter
- A static method
- A constructor
- A private method
If you override == you should also override…
- toString
- hashCode
- runtimeType
- noSuchMethod