From language to practice
You now know Dart the language. This lesson is about Dart the practice: how real projects are laid out and share code through packages, how teams keep thousands of files consistent with the analyzer and the formatter, how they prove code works with tests, and how Flutter, the reason most people meet Dart, turns classes into user interfaces. It ends with a complete program, written as a professional would write it, that brings together almost everything in the course.
Packages and pub
Every Dart project is a package: a folder with a pubspec.yaml file. dart create made one in the first lesson; its pubspec.yaml read:
name: deliveries
description: A sample command-line application.
version: 1.0.0
environment:
sdk: ^3.14.1
dependencies:
path: ^1.9.0
dev_dependencies:
lints: ^6.0.0
test: ^1.25.6dependencies are packages the program needs to run; dev_dependencies are needed only during development, such as the test framework and the lint rules. Version constraints use the caret: ^1.9.0 means "1.9.0 or any later 1.x", trusting that the package follows semantic versioning and saves breaking changes for a new major version. The tool is pub:
| Command | What it does |
|---|---|
dart pub add http | add the latest compatible version of a package to dependencies |
dart pub add --dev mocktail | add one to dev_dependencies |
dart pub get | download everything into the shared pub cache and write pubspec.lock |
dart pub upgrade | move to the newest versions the constraints allow |
dart pub outdated | list dependencies with newer versions available |
pubspec.lock records the exact version of every package that was resolved. Commit it for applications, so every developer and the build server use the same versions. Packages are published to pub.dev, the official repository, which shows each package's supported platforms, documentation, a score based on automated checks, and whether it comes from a verified publisher. Before adding a dependency, professionals check that it is maintained and widely used, because every dependency is code you are trusting.
Inside a package, the layout is a convention that the tools rely on:
lib/holds the library code. Other packages import it aspackage:deliveries/deliveries.dart. Implementation files conventionally go inlib/src/, which other packages should not import directly; the public file inlib/exports what users may see.bin/holds executables, run withdart run.test/holds tests, files ending in_test.dart.
The analyzer, lints and the formatter
The analyzer checks your code for errors and warnings, and also for lints: rules about style and likely mistakes, configured in analysis_options.yaml. A new package includes the Dart team's recommended set:
include: package:lints/recommended.yamlFlutter projects use package:flutter_lints instead, and many teams add stricter rules or enable the analyzer's strict-casts and strict-inference modes. Here is what a lint looks like. Adding a function that tests d.problems.length == 0 to the project's library made dart analyze report:
info - lib/deliveries.dart:141:7 - Use 'isEmpty' instead of 'length' to test whether the collection is empty. Try rewriting the expression to use 'isEmpty'. - prefer_is_emptyand dart fix --dry-run offered to rewrite it automatically with dart fix --apply. Editors show the same diagnostics as you type, with quick fixes.
dart format rewrites code into the one official style. Since Dart 3.7 the formatter uses a "tall" style that puts arguments one per line when they do not fit, and since 3.8 it also decides where trailing commas go. Teams run it on save and check it in continuous integration (dart format --output=none --set-exit-if-changed . fails if anything is unformatted), so style never comes up in code review. Every program in this course was run through it.
Testing with package:test
Tests live in test/, use package:test, and run with dart test. Here are tests for the project at the end of this lesson, after its domain code was moved into lib/deliveries.dart:
import 'package:deliveries/deliveries.dart';
import 'package:test/test.dart';
void main() {
group('parseEvent', () {
test('reads a valid order', () {
final event = parseEvent({
'type': 'ordered',
'order': 'A1',
'at': 540,
'items': 3,
});
expect(event, isA<Ordered>().having((e) => e.items, 'items', 3));
});
test('rejects a time that is not a number', () {
expect(
() => parseEvent({
'type': 'ordered',
'order': 'D4',
'at': 'noon',
'items': 2,
}),
throwsA(isA<FormatException>()),
);
});
});
group('Dashboard', () {
late Dashboard dashboard;
setUp(() => dashboard = Dashboard());
test('accepts the normal life of an order', () {
expect(dashboard.apply(const Ordered('A1', 540, 3)), isTrue);
expect(dashboard.apply(const Dispatched('A1', 560, 'Femi')), isTrue);
expect(dashboard.apply(const Delivered('A1', 602)), isTrue);
expect(dashboard.problems, isEmpty);
});
test('refuses to deliver a cancelled order', () {
dashboard
..apply(const Ordered('B2', 545, 1))
..apply(const Cancelled('B2', 600, 'address not found'));
expect(dashboard.apply(const Delivered('B2', 640)), isFalse);
expect(dashboard.problems.single, contains('not allowed when cancelled'));
});
});
}test declares a test with a description; group gathers related tests, and the descriptions combine in the output. setUp runs before each test in its group, so every test gets a fresh Dashboard (the late variable is assigned there). expect(actual, matcher) checks a value against a matcher: isTrue, isEmpty, contains, isA of a type, refined with having to check a property, and throwsA for code that should throw. Running dart test printed:
00:00 +0: loading test/deliveries_test.dart
00:00 +0: test/deliveries_test.dart: parseEvent reads a valid order
00:00 +1: test/deliveries_test.dart: parseEvent rejects a time that is not a number
00:00 +2: test/deliveries_test.dart: Dashboard accepts the normal life of an order
00:00 +3: test/deliveries_test.dart: Dashboard refuses to deliver a cancelled order
00:00 +4: All tests passed!The +4 counts passing tests. Notice what the tests target: the pure logic (parseEvent, Dashboard.apply), not the printing. Keeping logic in plain functions and classes, separate from input and output, is what makes code testable, in Dart and everywhere else. Asynchronous code is tested the same way, with async test functions. Flutter adds flutter_test, whose widget tests pump a widget tree in a test environment and tap its buttons, and integration tests that drive a real device.
Flutter's widget model
In Flutter, everything on the screen is described by widgets: immutable Dart objects that say what a piece of the interface should look like for the current state. Text, padding, rows, buttons, whole screens: all widgets, composed into a tree. When state changes, Flutter calls your build methods again to get a new description, compares it with the previous one, and updates only what changed on screen. You never modify a button; you describe a new one.
Here is a complete counter app. It needs the Flutter SDK (or DartPad's Flutter mode), so it is shown as plain code:
import 'package:flutter/material.dart';
void main() => runApp(const CounterApp());
class CounterApp extends StatelessWidget {
const CounterApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: CounterPage());
}
}
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Text(
'Tapped $_taps times',
style: Theme.of(context).textTheme.headlineMedium,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _taps++),
child: const Icon(Icons.add),
),
);
}
}Every Dart feature in it is one you know. A StatelessWidget has only final configuration and a build method; CounterApp is one. A StatefulWidget pairs an immutable widget with a separate, long-lived State object that holds mutable data, here _taps (private, by its underscore). Calling setState tells Flutter that the state changed, so it calls build again. The tree is a nest of constructor calls with named parameters (appBar:, body:, child:, onPressed:), and const marks subtrees that never change, so Flutter can skip rebuilding them. super.key passes an optional key up to the superclass constructor with a super parameter (Dart 2.17). BuildContext is the widget's position in the tree, used to look up inherited data such as the theme.
Real apps keep business logic out of widgets, in plain Dart classes (like the Dashboard below) exposed to the UI through a state-management approach; Flutter's own documentation discusses the options. And the development loop is what makes Flutter popular: change the code, save, and hot reload injects it into the running app in about a second, keeping its state, thanks to the Dart VM's JIT.
Reading JSON
Real data arrives as text, very often JSON. dart:convert turns JSON text into Dart maps, lists, strings, numbers, booleans and null, and back:
import 'dart:convert';
void main() {
// Each line is one JSON object, as a log file or a server might send them.
const lines = '''
{"type": "ordered", "order": "A1", "at": 540, "items": 3}
{"type": "delivered", "order": "A1", "at": 602}
{"type": "ordered", "order": "B2", "at": 545,
''';
for (final line in const LineSplitter().convert(lines.trim())) {
try {
final decoded = jsonDecode(line);
// jsonDecode returns dynamic: check its shape with a pattern before trusting it.
if (decoded case {'type': String type, 'order': String order}) {
print('$type $order (${decoded.length} fields)');
}
} on FormatException catch (e) {
print('bad JSON: ${e.message}');
}
}
final summary = {
'orders': 2,
'couriers': ['Femi', 'Ines'],
'average': 55.5,
};
print(jsonEncode(summary));
print(
const JsonEncoder.withIndent(' ').convert({'ok': true, 'missing': null}),
);
}ordered A1 (4 fields)
delivered A1 (3 fields)
bad JSON: Unexpected end of input
{"orders":2,"couriers":["Femi","Ines"],"average":55.5}
{
"ok": true,
"missing": null
}jsonDecode returns dynamic, because it cannot know the shape of the text in advance, and it throws a FormatException on malformed input, like the truncated third line. That is exactly where patterns earn their keep: check the decoded value's shape once, with a map pattern, and continue with properly typed variables. jsonEncode goes the other way, and JsonEncoder.withIndent makes it readable. Larger apps generate this conversion code with json_serializable, but the principle is the same: untyped at the edge, typed everywhere inside.
The project: a delivery dashboard
Example— From raw events to a report
A small delivery service records events as JSON objects: an order is placed, dispatched with a courier, delivered or cancelled. The events arrive as a stream, some of them malformed, some impossible (delivering an order that was cancelled). The program must keep track of every order, report delivery times and courier activity, and list the problems instead of crashing on them. The events below stand in for decoded JSON arriving over the network; times are minutes after midnight.
// Delivery dashboard: turn a stream of raw JSON-like events into a report.
// ---- The domain: a sealed family of events -------------------------------
sealed class Event {
final String order;
final int at; // minutes since midnight
const Event(this.order, this.at);
}
class Ordered extends Event {
final int items;
const Ordered(super.order, super.at, this.items);
}
class Dispatched extends Event {
final String courier;
const Dispatched(super.order, super.at, this.courier);
}
class Delivered extends Event {
const Delivered(super.order, super.at);
}
class Cancelled extends Event {
final String reason;
const Cancelled(super.order, super.at, this.reason);
}
/// Parses one decoded JSON object, or throws a [FormatException].
Event parseEvent(Map<String, Object?> json) => switch (json) {
{'type': 'ordered', 'order': String o, 'at': int t, 'items': int n}
when n > 0 =>
Ordered(o, t, n),
{'type': 'dispatched', 'order': String o, 'at': int t, 'courier': String c} =>
Dispatched(o, t, c),
{'type': 'delivered', 'order': String o, 'at': int t} => Delivered(o, t),
{'type': 'cancelled', 'order': String o, 'at': int t, 'reason': String r} =>
Cancelled(o, t, r),
_ => throw FormatException('unrecognised event', json),
};
extension ClockTime on int {
String get clock =>
'${(this ~/ 60).toString().padLeft(2, '0')}:${(this % 60).toString().padLeft(2, '0')}';
}
// ---- The state of each order ---------------------------------------------
enum Status { placed, onTheWay, delivered, cancelled }
class Order {
final String id;
final int placedAt;
final int items;
Status status = Status.placed;
String? courier;
int? deliveredAt;
Order(this.id, this.placedAt, this.items);
}
class Dashboard {
final _orders = <String, Order>{};
final problems = <String>[];
/// Applies [event] and returns whether it was accepted.
bool apply(Event event) {
final problemsBefore = problems.length;
final order = _orders[event.order];
switch ((event, order)) {
case (Ordered(:final order, :final at, :final items), null):
_orders[order] = Order(order, at, items);
case (Ordered(), _):
problems.add('${event.order}: ordered twice');
case (_, null):
problems.add('${event.order}: event for an unknown order');
case (Dispatched(:final courier), final Order o)
when o.status == Status.placed:
o
..status = Status.onTheWay
..courier = courier;
case (Delivered(:final at), final Order o)
when o.status == Status.onTheWay:
o
..status = Status.delivered
..deliveredAt = at;
case (Cancelled(), final Order o) when o.status != Status.delivered:
o.status = Status.cancelled;
case (_, final Order o):
problems.add(
'${o.id}: ${event.runtimeType} not allowed when ${o.status.name}',
);
}
return problems.length == problemsBefore;
}
void report() {
final counts = <Status, int>{for (final s in Status.values) s: 0};
for (final o in _orders.values) {
counts[o.status] = counts[o.status]! + 1;
}
print('Orders: ${_orders.length}');
for (final MapEntry(:key, :value) in counts.entries) {
print(' ${key.name.padRight(10)} $value');
}
final times = [
for (final o in _orders.values)
if (o.deliveredAt case final done?)
(id: o.id, minutes: done - o.placedAt, courier: o.courier!),
]..sort((a, b) => a.minutes.compareTo(b.minutes));
if (times.isNotEmpty) {
final average =
times.map((t) => t.minutes).reduce((a, b) => a + b) / times.length;
print(
'Delivery time: fastest ${times.first.minutes} min (${times.first.id}), '
'slowest ${times.last.minutes} min (${times.last.id}), average ${average.toStringAsFixed(1)} min',
);
final byCourier = <String, int>{};
for (final t in times) {
byCourier.update(t.courier, (n) => n + 1, ifAbsent: () => 1);
}
final ranking = byCourier.entries.toList()
..sort((a, b) => b.value.compareTo(a.value));
print(
'Deliveries by courier: ${ranking.map((e) => '${e.key} ${e.value}').join(', ')}',
);
final items = _orders.values
.where((o) => o.status == Status.delivered)
.fold(0, (sum, o) => sum + o.items);
print('Items delivered: $items');
}
print('Problems (${problems.length}):');
for (final p in problems) {
print(' $p');
}
}
}
// ---- Input: a stream of decoded JSON objects -------------------------------
Stream<Map<String, Object?>> incoming() async* {
const log = <Map<String, Object?>>[
{'type': 'ordered', 'order': 'A1', 'at': 540, 'items': 3},
{'type': 'ordered', 'order': 'B2', 'at': 545, 'items': 1},
{'type': 'dispatched', 'order': 'A1', 'at': 560, 'courier': 'Femi'},
{'type': 'ordered', 'order': 'C3', 'at': 570, 'items': 2},
{'type': 'dispatched', 'order': 'B2', 'at': 575, 'courier': 'Ines'},
{'type': 'delivered', 'order': 'A1', 'at': 602},
{'type': 'dispatched', 'order': 'C3', 'at': 590, 'courier': 'Femi'},
{'type': 'delivered', 'order': 'Z9', 'at': 610},
{
'type': 'cancelled',
'order': 'B2',
'at': 600,
'reason': 'address not found',
},
{'type': 'delivered', 'order': 'C3', 'at': 619},
{'type': 'ordered', 'order': 'D4', 'at': 'noon', 'items': 2},
{'type': 'delivered', 'order': 'B2', 'at': 640},
{'type': 'ordered', 'order': 'E5', 'at': 630, 'items': 4},
];
for (final json in log) {
await Future<void>.delayed(
Duration.zero,
); // as if each arrived from the network
yield json;
}
}
Future<void> main() async {
final dashboard = Dashboard();
var line = 0;
await for (final json in incoming()) {
line++;
try {
final event = parseEvent(json);
if (dashboard.apply(event) && event is Delivered) {
print('${event.at.clock} ${event.order} delivered');
}
} on FormatException catch (e) {
dashboard.problems.add('line $line: ${e.message}');
}
}
print('');
dashboard.report();
}10:02 A1 delivered
10:19 C3 delivered
Orders: 4
placed 1
onTheWay 0
delivered 2
cancelled 1
Delivery time: fastest 49 min (C3), slowest 62 min (A1), average 55.5 min
Deliveries by courier: Femi 2
Items delivered: 5
Problems (3):
Z9: event for an unknown order
line 11: unrecognised event
B2: Delivered not allowed when cancelledRead it as a tour of the course:
- A sealed family (
Event, with four subclasses using super parameters such assuper.order) models the four kinds of event, each with exactly its own data. - Patterns at the boundary.
parseEventvalidates each raw map with one map pattern per event type, plus awhenguard on the item count, and throws aFormatExceptionfor anything else. Line 11 ('at': 'noon') is rejected there, and everything after that line works with typed objects. - A switch over a record in
Dashboard.applymatches the pair of the new event and the current order,(event, order), so one switch expresses the whole state machine: anOrderedevent with no existing order, any event for an unknown order, dispatch only fromplaced, delivery only fromonTheWay, cancellation unless delivered, and a final case that records everything else as a problem. Cases are tried in order, so the general cases come last. - An enum (
Status), an extension (clockonint), cascades to update two fields at once, and a record list with named fields ((id:, minutes:, courier:)) built by a collectionforwith anif-case, then sorted. - Collections: a map built with a
forelement overStatus.values,updatewithifAbsentto count deliveries per courier,foldto total the items. - Asynchrony: the input is a stream from an
async*function, consumed withawait for, and malformed events are handled withtryandon FormatExceptionwithout stopping the stream.
Moving the domain code into lib/deliveries.dart and the stream and main into bin/deliveries.dart turned it into the package tested above; dart analyze with the recommended lints reported no issues, and dart run printed the same report. Natural next steps: read real JSON lines from a file with dart:io and jsonDecode, compute statistics per hour, and put a Flutter screen on top of the same Dashboard class.
A closing thought
Optional Christian reflection · Giving up a little for the sake of others
A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.
Dart teams do not argue about brace placement, line length or trailing commas: the formatter decides, and everyone accepts its choices, even the ones they would not have made. Each developer gives up a small personal preference, and in return the whole community can read each other's code without friction. The same spirit runs through lint rules, shared conventions and careful package versioning: small acts of consideration for people you may never meet. Christians will recognize an old counsel there, to look not only to your own interests but also to the interests of others. It applies to code as well as to life, and good tools make it easier to follow.
Where to go next
- Effective Dart: the style, documentation, usage and design guides. Reread it now that you know the whole language.
- The Dart language tour and library tour on dart.dev, for the details this course skipped (generators,
dart:collection,Uri, regular expressions, thecharacterspackage). - Flutter's documentation, starting with its fundamentals, if user interfaces are your goal; DartPad runs small Flutter apps in the browser.
- pub.dev: read the source of well-regarded packages from the Dart and Flutter teams; it is the best way to absorb professional style.
- The Dart SDK and language repositories on GitHub, where features are proposed, specified and discussed in the open.
Exercises
1. Packages, tests, Flutter and a project
Warm-upHumanYour command-line tool uses package:http when it runs and package:test only for its tests. Where should each go in pubspec.yaml?
2. Packages, tests, Flutter and a project
CoreHumanA dependency is declared as ^2.3.1. Which of these versions satisfy the constraint? List the letters.
- A. 2.3.0
- B. 2.3.1
- C. 2.9.4
- D. 3.0.0
- E. 2.10.0
3. Packages, tests, Flutter and a project
CoreComputationalWhat does this program print?
import 'dart:convert';
void main() {
print(jsonDecode('[1, {"a": null}]'));
}
4. Packages, tests, Flutter and a project
StretchComputationalIn the project, suppose the event that cancels order B2 is removed from the log and nothing else changes. How many problems does the report list?
5. Packages, tests, Flutter and a project
CoreHumanIn the Flutter counter, what does setState(() => _taps++) do that a plain _taps++ would not?
6. Packages, tests, Flutter and a project
Warm-upHumanWhich command reformats every Dart file in the current package in the official style? Type the whole command.
7. Packages, tests, Flutter and a project
Warm-upHumanA dart test run ends with 00:00 +4: All tests passed!. What does +4 mean?