Explain it simply
Explain it simply
Look back at the tutorial and you will find that every lesson added one tool: a type, a loop, a collection, a class, a Future. This summary adds no new syntax. It shows those tools working together in one small program, the way they work in real projects, and then helps you decide where to go next.
A kitchen makes it easy to picture. Knives, pans and ovens are the individual lessons. A dinner is the moment they cooperate: the order in which you use them, and what happens when an ingredient is missing, matters more than owning each tool. The capstone below is that dinner.
Problem → Why → Solution
The problem: knowing the features but having no plan to combine them
You can answer each lesson's quiz and still freeze when asked to write a program that needs five of them at once. The usual fallback is a habit from the first weeks: keep everything in dynamic maps and never await anything.
The snippet below does both. It compiles, but the second line crashes with a NoSuchMethodError, and because the program stops there, the unfinished save never gets a chance to print.
Map<String, dynamic> ticket = {'id': 1, 'agent': null};
Future<void> save(Map<String, dynamic> t) async {
await Future<void>.delayed(const Duration(milliseconds: 5));
print('saved ${t['id']}');
}
void main() {
save(ticket); // returns a Future, and nobody awaits it
print(ticket['agent'].length); // dynamic: compiles, crashes at runtime
}Why combining features needs a plan
Each feature is safe on its own, but the safety comes from the types: a typed Ticket class with a String? agent forces you to handle null, and an awaited Future keeps the order of events clear. When you drop the types, you give up all of that help at once. The cure is not a new feature but a few habits: model data with classes, make absence visible with ?, return Futures and await them, and let the compiler check every case.
Core concept: five ideas that hold the language together
Dart looks large, but a handful of ideas explain most of what you will read in the capstone.
1. Types describe shape and absence
A String and a String? are different types, so the compiler knows where null can appear. Use ?? to supply a default, ?. to skip a call, and a null check to promote the type. Avoid the ! operator and dynamic, because each one trades a compile-time check for a possible runtime crash.
2. Classes model things, sealed classes model choices
An ordinary class groups fields and behaviour. A sealed class lists every possible subtype in one library, so a switch over it must cover each case. Add a new subtype and the compiler points at every switch that needs updating.
3. Collections hold many, records return several
Lists, maps and sets store values; collection-for and spread build them; sort and where reshape them. A record such as (assigned: 4, failed: 1) returns several values together without declaring a class, and patterns take it apart again.
4. Futures and Streams model waiting
A Future is one value that arrives later; a Stream is many. await pauses only the current function, and an error thrown inside an async function reappears at the await, where try and on can catch it like any other exception.
5. Tooling keeps you honest
dart format, dart analyze and dart test run in seconds. Run them before you trust any output.
| Lesson topic | Where it shows up in the capstone |
|---|---|
| Enums with fields | Priority carries a weight used for sorting |
| Null safety | requestedAgent is String?, resolved with ?? |
| Sealed classes and patterns | Outcome and the switch inside describe() |
| Extension methods | byUrgency() on Iterable<Ticket> |
| Streams and async/await | incoming() yields tickets and main awaits each one |
| Records | The counts value with three named fields |
- Model data with classes and enums
- Make absence visible with ?
- Model each result as a sealed case
- Await async work, catch with try/on
- Summarize with records and patterns
Each step removes one kind of surprise: unclear data, hidden null, forgotten cases, lost errors and scattered results.
General pattern
sealed class Result {}
class Ok extends Result {
Ok(this.value);
final int value;
}
class Err extends Result { Err(this.message); final String message; }
String show(Result r) => switch (r) {
Ok(:final value) => 'ok $value',
Err(:final message) => 'error: $message',
};One sealed base class, one subclass per kind of result, and a switch expression that takes each one apart with a pattern. If a variant is missing, the code does not compile.
Support desk capstone: tickets, agents and outcomes
The program below is a tiny support desk. Tickets arrive one by one on a Stream, most urgent first. Each ticket either gets an agent, is skipped because its title is blank, or fails because the requested agent is full. Every ticket ends as exactly one Outcome, and a switch expression turns each outcome into a line of text. Read it top to bottom: data and types first, then the async desk, then main.
enum Priority {
low(1),
normal(2),
urgent(3);
const Priority(this.weight);
final int weight;
}
class Ticket {
const Ticket(this.id, this.title, this.priority, {this.requestedAgent});
final int id;
final String title;
final Priority priority;
final String? requestedAgent; // null means "anyone"
}
sealed class Outcome {
const Outcome(this.ticket);
final Ticket ticket;
}
class Assigned extends Outcome {
const Assigned(super.ticket, this.agent);
final String agent;
}
class Skipped extends Outcome {
const Skipped(super.ticket, this.reason);
final String reason;
}
class Failed extends Outcome {
const Failed(super.ticket, this.message);
final String message;
}
extension TicketOrder on Iterable<Ticket> {
/// Most urgent first; equal priorities keep id order.
List<Ticket> byUrgency() => toList()
..sort((a, b) {
final byPriority = b.priority.weight.compareTo(a.priority.weight);
return byPriority != 0 ? byPriority : a.id.compareTo(b.id);
});
}
class Desk {
Desk(this._capacity);
final Map<String, int> _capacity;
Future<String> reserve(String? preferred) async {
await Future<void>.delayed(const Duration(milliseconds: 5));
final name = preferred ?? _mostFree();
final free = _capacity[name];
if (free == null) throw StateError('unknown agent "$name"');
if (free == 0) throw StateError('$name is fully booked');
_capacity[name] = free - 1;
return name;
}
String _mostFree() {
final entries = _capacity.entries.toList()
..sort((a, b) {
final byFree = b.value.compareTo(a.value);
return byFree != 0 ? byFree : a.key.compareTo(b.key);
});
return entries.first.key;
}
}
Stream<Ticket> incoming(List<Ticket> tickets) async* {
for (final ticket in tickets) {
await Future<void>.delayed(const Duration(milliseconds: 5));
yield ticket;
}
}
String describe(Outcome outcome) => switch (outcome) {
Assigned(:final ticket, :final agent) => '#${ticket.id} -> $agent',
Skipped(:final ticket, :final reason) => '#${ticket.id} skipped ($reason)',
Failed(:final ticket, :final message) => '#${ticket.id} FAILED: $message',
};
Future<void> main() async {
final queue = [
const Ticket(1, 'Printer jammed', Priority.low),
const Ticket(2, 'Server down', Priority.urgent, requestedAgent: 'Mya'),
const Ticket(3, '', Priority.normal),
const Ticket(4, 'VPN broken', Priority.urgent, requestedAgent: 'Zaw'),
const Ticket(5, 'New laptop', Priority.normal),
const Ticket(6, 'Reset password', Priority.urgent, requestedAgent: 'Mya'),
];
final desk = Desk({'Aye': 1, 'Mya': 1, 'Zaw': 2});
final outcomes = <Outcome>[];
await for (final ticket in incoming(queue.byUrgency())) {
if (ticket.title.trim().isEmpty) {
outcomes.add(Skipped(ticket, 'blank title'));
continue;
}
try {
outcomes.add(Assigned(ticket, await desk.reserve(ticket.requestedAgent)));
} on StateError catch (e) {
outcomes.add(Failed(ticket, e.message));
}
}
outcomes.map(describe).forEach(print);
final counts = (
assigned: outcomes.whereType<Assigned>().length,
skipped: outcomes.whereType<Skipped>().length,
failed: outcomes.whereType<Failed>().length,
);
print('assigned=${counts.assigned} skipped=${counts.skipped} '
'failed=${counts.failed}');
final perAgent = <String, List<int>>{};
for (final Assigned(:ticket, :agent) in outcomes.whereType<Assigned>()) {
perAgent.putIfAbsent(agent, () => []).add(ticket.id);
}
print(perAgent);
}Code breakdown
- Enum with a field
const Priority(this.weight);Enhanced enums can carry data. Each Priority has a weight, and the sorting extension compares weights, so no magic numbers are scattered through the program.
- Nullable on purpose
final String? requestedAgent;The ? says some tickets name no agent. Elsewhere the code resolves it with preferred ?? _mostFree(), so the compiler forces every use to deal with the null case.
- A closed set of results
sealed class Outcome {Outcome can only be extended inside this library, so the compiler knows the complete list: Assigned, Skipped and Failed. A switch over an Outcome that misses one is a compile error, and adding a default branch would hide exactly that protection.
- Extension method
List<Ticket> byUrgency() => toList()An extension on Iterable adds a method to an existing type without subclassing. toList() copies first, so the caller's list is not reordered. Dart's sort is not guaranteed to be stable, so equal priorities fall back to the id and the order is fully determined.
- Async failure, caught at the await
} on StateError catch (e) {reserve is async, so it returns a Future<String>. Throwing a StateError inside it completes that Future with an error instead of crashing the caller immediately. The error reappears at the await line, the on StateError clause turns it into a Failed outcome, and the loop carries on with the next ticket.
- A Stream of tickets
Stream<Ticket> incoming(List<Ticket> tickets) async* {async* marks a generator that produces a Stream, and yield emits one value at a time. The await for loop in main receives each value as it arrives. The 5 ms delays imitate waiting.
- Pattern-based switch
Assigned(:final ticket, :final agent) => '#${ticket.id} -> $agent',The object pattern takes an Assigned apart and binds ticket and agent in one step. Because Outcome is sealed, the switch expression must cover all three cases and gives back a value.
#2 -> Mya
#4 -> Zaw
#6 FAILED: Mya is fully booked
#3 skipped (blank title)
#5 -> Aye
#1 -> Zaw
assigned=4 skipped=1 failed=1
{Mya: [2], Zaw: [4, 1], Aye: [5]}- Ticket arrives on the Stream
- Blank title? Record Skipped
- Ask the desk to reserve an agent (await)
- Reservation succeeds: record Assigned
- StateError thrown: record Failed
- After the loop: describe each outcome, print the counts
Assigned
Agent reserved, capacity drops by one
Failed or Skipped
Recorded as an outcome, the loop goes on
Reading the capstone's output
Trace the output line by line, because tracing is the skill this lesson trains. Tickets are sorted by urgency first, so the three urgent ones (ids 2, 4 and 6) go before the normal ones (3 and 5), and the low one (1) goes last. Mya has room for one ticket, so ticket 2 takes it and ticket 6, which also asks for Mya, fails with 'Mya is fully booked'. Ticket 3 has a blank title and is skipped before the desk is even asked. Ticket 5 names no agent, so the desk picks whoever has the most free slots; Aye and Zaw are tied at one, and the alphabetical order of their names lets Aye win. Ticket 1 goes to Zaw, the only agent left with a free slot.
The last two lines come from a record and a map. The counts record holds assigned, skipped and failed as named fields (assigned=4 skipped=1 failed=1). The perAgent map groups ticket ids by agent with putIfAbsent, and the for loop takes each Assigned apart with a pattern, which is why Zaw lists [4, 1]: ticket 4 arrived before ticket 1.
Choosing what to learn next
There is no single correct path. Pick the row that matches what you want to build and start a small project in that area this week. A project you care about teaches more than finishing another course.
| Goal | Next step |
|---|---|
| Build mobile or desktop apps | Flutter: widgets, state management and layouts, all written in Dart |
| Write command-line tools or servers | dart:io, command-line arguments and a server package such as shelf |
| Trust your code | package:test, dart analyze and a stricter analysis_options.yaml |
| Speed up heavy computation | Isolates: Isolate.run for CPU-bound work |
| Reuse and share code | Packages: pubspec.yaml, pub.dev and publishing your own |
| Write code others enjoy reading | The Effective Dart guide and the lints in the official docs |
In real projects
In real projects
Flutter apps are this capstone with widgets on top. Models are immutable classes, repositories return Futures or Streams, and a common pattern is to describe screen state as a sealed class such as Loading, Data and Failure that a switch turns into widgets; the exhaustive switch is what guarantees the screen handles every state. Servers written in Dart have the same bones: a request arrives, you validate it into a typed object, await a database call, and produce one of a few known outcomes.
Teams add the tooling layer on top: dart format in the editor, dart analyze and dart test in continuous integration, so the checks you learned to run by hand run on every change automatically.
Common mistakes
Common mistakes
Silencing the compiler with ! and dynamic
Each ! asserts that a value is not null and crashes at runtime if you are wrong, and dynamic turns off checking for everything it touches. Prefer ??, ?., a null check that promotes the variable, or an early return, and give data a class instead of a dynamic map.
Not awaiting a Future
Calling an async function without await starts it and moves on. Its result is a Future instead of a value, any error it throws escapes your try block, and later lines may run before the work finishes. The unawaited_futures lint can warn you. If you really mean fire-and-forget, say so deliberately; otherwise await it.
Adding a default branch to a switch over a sealed class
A wildcard or default branch makes the switch compile no matter how many subtypes exist, so a new subtype silently falls into it. List every case and let the compiler warn you when one is missing.
Treating one passing run as proof
A program that prints the right answer for one input has only been checked for that input. Try an empty list, a tie, a null and a failing async call before you call it done.
Mini challenge
Grade book: averages from a stream of records
Write averageScores, which consumes a Stream of (String, int?) records, one per score event. Skip null scores and scores outside 0 to 100, group the valid scores by student, and return a Map of student to average rounded to one decimal, with keys in alphabetical order.
- averageScores is async and reads the stream with await for
- Null scores and scores outside 0..100 are ignored; a student with no valid score does not appear
- Averages are rounded to one decimal and the keys are sorted alphabetically
- main prints the result for a sample feed and for an empty stream
Stream<(String, int?)> feed() async* {
// TODO: yield these records, a few milliseconds apart:
// ('Mya', 70), ('Aye', 90), ('Zaw', null), ('Aye', 81),
// ('Zaw', 100), ('Mya', 105), ('Hla', -5), ('Nandar', null)
}
Future<Map<String, double>> averageScores(Stream<(String, int?)> events) async {
// TODO: collect the valid scores per student with await for
// TODO: build the averages (one decimal), keys in alphabetical order
}
Future<void> main() async {
// TODO: print the result for feed() and for an empty stream
}Expected: {Aye: 85.5, Mya: 70.0, Zaw: 100.0} followed by {}. Hla (invalid score) and Nandar (only a null score) do not appear.
Show hint
await for (final (student, score) in events) destructures the record right in the loop head. The score can be null, so test score == null before comparing it. For one decimal, double.parse(value.toStringAsFixed(1)) works.
Show solution
typedef ScoreEvent = (String, int?);
Stream<ScoreEvent> feed() async* {
const events = <ScoreEvent>[
('Mya', 70),
('Aye', 90),
('Zaw', null),
('Aye', 81),
('Zaw', 100),
('Mya', 105),
('Hla', -5),
('Nandar', null),
];
for (final event in events) {
await Future<void>.delayed(const Duration(milliseconds: 3));
yield event;
}
}
double average(List<int> values) {
final sum = values.fold<int>(0, (total, value) => total + value);
return double.parse((sum / values.length).toStringAsFixed(1));
}
Future<Map<String, double>> averageScores(Stream<ScoreEvent> events) async {
final valid = <String, List<int>>{};
await for (final (student, score) in events) {
if (score == null || score < 0 || score > 100) continue;
valid.putIfAbsent(student, () => <int>[]).add(score);
}
final entries = valid.entries.toList()..sort((a, b) => a.key.compareTo(b.key));
return {for (final entry in entries) entry.key: average(entry.value)};
}
Future<void> main() async {
print(await averageScores(feed()));
print(await averageScores(Stream<ScoreEvent>.empty()));
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Types make absence visible, and ! and dynamic give that protection up
- A sealed class with a switch expression lets the compiler check every case
- Collections, records and patterns gather and unpack results without extra classes
- Async errors reappear at await so try/on can catch them; pick your next step by your own goal
Dart language overview — Dart