Explain it simply
Explain it simply
A class is like the blueprint for a house. It says every house has facts such as a number of rooms and a colour (fields) and things it can do such as open the door (methods). Each house built from that blueprint is an object: every house has its own colour and its own room count, but all of them share the same shape.
In Dart numbers, strings and lists are all objects already. Writing your own class adds your app's vocabulary to the language: "Course", "User", "Order". The code then reads precisely, as course.title, instead of passing around loose text keys in a map.
Problem → Why → Solution
The problem: a Map checks nothing about your data
You are modelling courses for a learning app. The quick way is a Map: {'title': 'Dart Basics', 'lessons': 18}. It works until the second course arrives with a typo in a key and a number stored as text. Dart accepts both without complaint: reading 'title' quietly gives null and comparing the lessons with 24 quietly gives false. There is no autocomplete for keys, nothing says which keys must exist, and a map cannot carry behaviour such as "publish this course".
What you want is a named shape with fixed fields whose types the compiler checks, together with the functions that belong to that shape. That is exactly what a class gives you.
void main() {
final course = {'title': 'Dart Basics', 'lessons': 18};
final other = {'titel': 'Flutter', 'lessons': '24'}; // typo, and the number is text
print(course['lessons']);
print(other['title']); // null: nothing warns you
print(other['lessons'] == 24); // false: it is the text '24'
}What does a class change?
A class turns an informal agreement ("every course map has a title and a number of lessons") into something the compiler enforces. A misspelled field name becomes a compile error instead of a silent null, and the field types stop a number from being stored as text.
Core concept: classes, instance and static members, getters and privacy
A class is a blueprint, and an object is one thing built from it. Fields hold the data (String title), methods hold the behaviour (void publish()), and each object gets its own copy of every field, so changing one course's lessons does not touch another's. You create an object by calling the constructor, Course('Dart Basics', 18); Dart does not need the new keyword, and style guides say to leave it out.
One class, two objects, one shared counter
------------------------------------------
class Course objects (own copy of each field)
+---------------+ basics --> title: 'Dart Basics' lessons: 18
| title | flutter --> title: 'Flutter' lessons: 0
| lessons |
| publish() | Course.created --> 2 (one value, shared)
+---------------+Members are instance members by default: they belong to a particular object, and inside them you read the other fields and methods of that same object by name (this. is optional). A static member belongs to the class itself: static int created is a single variable shared by all courses, and static String shortTitle(...) is a function that needs no object. You reach static members through the class name, Course.created, never through an instance, and a static method cannot read instance fields because there is no object to read them from. Use static for counters, constants (static const) and helpers that do not depend on one object's data.
A getter looks like a field when you read it but runs code: String get summary => '$title ($lessons lessons)' computes the text each time. A setter, set age(int value), looks like an assignment and can validate. Plain fields already behave like a getter and a setter, which is why you can start with a plain field and switch to a getter or setter later without changing a single call site. A final field has a getter only; assigning to it is a compile error.
Dart has no private or public keyword. A name that starts with an underscore, such as _published, is private to its library, and a library is normally one file, not one class. Any other class or function in the same file can read and write _published. To truly hide a field, put the class in its own file and import it from the others; other files then cannot even see the name.
- Class: the blueprint
- Object: one thing built from it
- Instance members: one copy per object
- static members: one copy for the class
Ask of every member: does it belong to one object, or to the class as a whole?
General pattern
class Name {
static int shared = 0; // one copy for the whole class
final String id; // each object has its own copy
int count = 0;
Name(this.id); // constructor
int get doubled => count * 2; // computed property
void action() { /* behaviour */ }
@override
String toString() => 'Name($id)';
}The class body holds fields, a constructor, getters / setters and methods. Every member that does not start with static is an instance member, and @override marks that you are replacing a member inherited from Object, such as toString.
Example: a Course class
This Course class has every important ingredient: a final field, a mutable field, a field hidden with an underscore, two getters, a method, and a static counter and static helper together with toString. main() creates two courses and shows that one of them cannot be published because it has no lessons. Predict what Course.created will be before you run it.
class Course {
static int created = 0;
final String title;
int lessons;
bool _published = false;
Course(this.title, this.lessons) {
created++;
}
bool get isPublished => _published;
String get summary => '$title ($lessons lessons)';
void publish() {
if (lessons == 0) {
print('cannot publish an empty course');
return;
}
_published = true;
}
static String shortTitle(String text) =>
text.length > 8 ? '${text.substring(0, 8)}...' : text;
@override
String toString() => 'Course($title, $lessons)';
}
void main() {
final basics = Course('Dart Basics', 18);
final flutter = Course('Flutter', 0);
print(basics);
print(basics.summary);
print(basics.isPublished);
basics.publish();
flutter.publish();
print(basics.isPublished);
basics.lessons = 20;
print(basics.summary);
print(Course.created);
print(Course.shortTitle(basics.title));
}Code breakdown
- Shared counter
static int created = 0;One static variable is shared by every course. created++ in the constructor increases it each time an object is created, so it is 2 after two courses, and you read it as Course.created.
- final vs mutable
final String title;A final field is set once, in the constructor, and has no setter: basics.title = 'x' is a compile error. The neighbouring int lessons is a plain field, so basics.lessons = 20 is allowed.
- Library-private field
bool _published = false;Because of the underscore, _published is visible only inside this file. Outside code cannot flip it directly and must call publish(), so the class itself can enforce the rule "no publishing without lessons".
- Read-only getter
bool get isPublished => _published;This is a property that outsiders may only read. With no setter, basics.isPublished = true is a compile error. You call it without parentheses, like a field: basics.isPublished.
- Guard in a method
if (lessons == 0) {publish() checks before it changes state. For the flutter course with no lessons it prints a message and returns, so _published stays false.
- Static helper
static String shortTitle(String text) =>It needs no object, so it is called as Course.shortTitle(...). There is no this, so it cannot read instance fields such as title or lessons and works only with its parameter.
- toString
String toString() => 'Course($title, $lessons)';print(basics) and string interpolation call toString(). Without the override you would see the unhelpful text "Instance of 'Course'".
Course(Dart Basics, 18)
Dart Basics (18 lessons)
false
cannot publish an empty course
true
Dart Basics (20 lessons)
2
Dart Bas...Making objects comparable: toString, == and hashCode
A class inherits three behaviours from Object: toString() gives "Instance of 'Money'", == tests identity only, and hashCode is based on identity. So two Money(5, 'USD') objects have equal contents but are not ==, and a Set keeps both. For classes whose value matters (Point, Money, Email) override == and hashCode together, building hashCode from exactly the fields that == compares with Object.hash(x, y). identical(a, b) is always there to test whether two references are the very same object.
class Money {
final int amount;
final String currency;
Money(this.amount, this.currency);
}
class Point {
final int x, y;
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);
@override
String toString() => 'Point($x, $y)';
}
void main() {
final m1 = Money(5, 'USD');
final m2 = Money(5, 'USD');
print(m1);
print(m1 == m2);
print({m1, m2}.length);
final p1 = Point(1, 2);
final p2 = Point(1, 2);
print(p1);
print(p1 == p2);
print(identical(p1, p2));
print({p1, p2}.length);
}| Member | Default behaviour | When to override |
|---|---|---|
| toString() | "Instance of 'ClassName'" | When you want readable text in debugging, logs and UI |
| == operator | Identity (same object) | Classes where equal values should count as equal |
| hashCode | Based on identity | Whenever you override ==, built from the same fields |
Library privacy and setters in practice
This Account class hides _balance with an underscore and lets it change only through the getter and deposit(). Yet the audit() function in the same file can change a._balance directly, because the underscore is library-level privacy, not class-level privacy. If you do not know that, you will be surprised after thinking the field was "locked inside the class". A setter is a natural place to validate: it rejects an invalid value such as limit = -5. Note that a getter is declared next to the setter here, which is what makes limit readable at all.
class Account {
double _balance = 0;
double _limit = 100;
double get balance => _balance;
double get limit => _limit;
set limit(double value) {
if (value < 0) {
throw ArgumentError('limit must not be negative');
}
_limit = value;
}
void deposit(double amount) {
if (amount <= 0) {
throw ArgumentError('deposit must be positive');
}
_balance += amount;
}
}
void audit(Account account) {
// Same file, so same library: the underscore does not stop this.
account._balance = 1000000;
}
void main() {
final account = Account();
account.deposit(50);
print(account.balance);
audit(account);
print(account.balance);
account.limit = 250;
print(account.limit);
try {
account.limit = -5;
} catch (e) {
print('caught: $e');
}
}In real projects
Where this shows up in real projects
Almost every Dart app is a collection of classes: User, Product and Order models that hold data parsed from JSON, services that talk to a server, and in Flutter every widget is a class. Getters keep derived values such as total or isEmpty in one place; the List class itself exposes isEmpty, length and first as getters. Static members hold constants and counters, for example static const maxRetries = 3.
Value-like classes such as Money or Email override == and hashCode so that two objects with equal contents behave as the same key in a Set or Map. toString shows up everywhere you debug, because print(object) and string interpolation call it. Keeping a class's fields final and its state changes behind a few methods makes it easy to reason about, which is the habit professional Dart code follows.
Common mistakes
Common mistakes
1. Believing an underscore hides a name from other classes
_balance is not private to the Account class; it is private to the whole file (library). Other classes and functions in the same file can read and write it. A class that needs real protection belongs in a file of its own that others import.
2. Overriding == without hashCode
If you override only == and leave hashCode alone, two objects with equal contents get different hashes, so a Set can keep both and a lookup with an equal Map key returns null. Write hashCode with Object.hash(x, y) over the same fields that == compares, and always change the two together.
3. Reaching a static member through an object, or an instance member through the class
Reading c.created through an instance gives "The getter 'created' isn't defined for the type 'Course'.", and reading an instance field through the class, as in Course.x, gives "Member not found: 'x'." Use the class name for static members, as in Course.created, and an object for instance members.
Best practices
Best practices
- Make fields final unless they truly need to change, and keep state changes behind a few methods.
- Expose derived values (total, isEmpty) as getters instead of storing them in separate fields, so they can never disagree with the other fields.
- Override toString on every class; debugging becomes much easier.
- Override == and hashCode together, and use the same fields in both.
Mini challenge
Mini challenge: a shopping cart
Write two classes, Product and Cart. A Product with the same name and price counts as equal, and the Cart refuses more than three items and refuses a product that is already in it.
- Product has a final name and an int price, and overrides ==, hashCode and toString (for example 'pen (2)')
- Cart has a static const maxItems = 3 and a private list with an underscore
- bool add(Product product) returns false when the cart is full or the product is already there, and otherwise adds it and returns true
- Write the getters itemCount and total, and a toString for Cart shaped like 'Cart(pen (2), book (12))'
- In main(), add pen(2), book(12), pen(2) again, lamp(30) and desk(90), print every add() result, then the cart, then the items and total
class Product {
// TODO: final name and price, set through the constructor
// TODO: override ==, hashCode and toString
}
class Cart {
// TODO: static const maxItems = 3
// TODO: a private list of products
// TODO: bool add(Product product): false when full or already present
// TODO: getters itemCount and total
// TODO: toString such as Cart(pen (2), book (12))
}
void main() {
// TODO: add pen(2), book(12), pen(2) again, lamp(30), desk(90) and print
// each add() result, then the cart, then "items: 3, total: 44"
}Expected: true true false true false Cart(pen (2), book (12), lamp (30)) items: 3, total: 44
Show hint
In Product's == write other is Product && other.name == name && other.price == price, and build hashCode with Object.hash(name, price). Inside Cart.add, _items.contains(product) uses ==, so an equal product is found. _items.join(', ') is handy for toString.
Show solution
class Product {
final String name;
final int price;
Product(this.name, this.price);
@override
bool operator ==(Object other) =>
other is Product && other.name == name && other.price == price;
@override
int get hashCode => Object.hash(name, price);
@override
String toString() => '$name ($price)';
}
class Cart {
static const maxItems = 3;
final List<Product> _items = [];
bool add(Product product) {
if (_items.length >= maxItems || _items.contains(product)) {
return false;
}
_items.add(product);
return true;
}
int get itemCount => _items.length;
int get total {
var sum = 0;
for (final item in _items) {
sum += item.price;
}
return sum;
}
@override
String toString() => 'Cart(${_items.join(', ')})';
}
void main() {
final cart = Cart();
print(cart.add(Product('pen', 2)));
print(cart.add(Product('book', 12)));
print(cart.add(Product('pen', 2)));
print(cart.add(Product('lamp', 30)));
print(cart.add(Product('desk', 90)));
print(cart);
print('items: ${cart.itemCount}, total: ${cart.total}');
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A class is a blueprint with fields and methods, and every object gets its own copy of each field.
- static members exist once per class and are reached through the class name; instance members are reached through an object.
- Getters and setters look like fields but run code, and an underscore makes a name private to the library (the file), not the class.
- Override toString, and override == together with hashCode, so objects print and compare the way you expect.
Dart language overview — Dart