Explain it simply
Explain it simply
This lesson combines the object-oriented chapters with null safety and async code. Each exercise is small, but in real applications these ideas never appear alone: a class hierarchy has fields that may be absent, and the objects often arrive from something slow such as a file or a server.
Picture a zoo registry. Animal is the blueprint every record follows. Dog and Bird are filled-in versions of it. Flyable is a skill badge that only some animals wear. Fetching a record takes time, because it comes from another office, and the office may answer 'no such animal'. Your tasks are to model this registry so the compiler helps in every one of those situations.
Problem → Why → Solution
The problem: a draft that looks fine and hides three bugs
A first draft of the registry usually looks fine and hides three bugs. The sound field is nullable, and reading its length after a null check does not compile when the field is public. The Dog constructor passes name and sound in the wrong order; both are Strings, so nothing complains and the dog says its name where the sound should be. And the async lookup is called without await, so the variable holds a Future instead of an animal.
The draft below has all three. Two of them stop the compiler; the swapped arguments do not, which makes that one the most dangerous.
class Animal {
Animal(this.name, this.sound);
final String name;
final String? sound;
int soundLength() {
if (sound != null) {
return sound.length; // error: a public field is not promoted
}
return 0;
}
}
class Dog extends Animal {
Dog(String name) : super('Woof', name); // swapped, and it still compiles
}
Future<Animal?> fetchAnimal(String key) async {
await Future<void>.delayed(const Duration(milliseconds: 40));
return key == 'rex' ? Dog('Rex') : null;
}
Future<void> main() async {
final animal = fetchAnimal('rex');
print(animal.name); // error: animal is a Future
}Three different kinds of failure
The first error is the compiler protecting you: a public field can be overridden by a subclass, possibly in another library, so two reads are not guaranteed to give the same value, and Dart will not trust the null check. The third is a type error: await is what turns a Future<Animal?> into an Animal?. The second is the dangerous one, because the types match even though the meaning is wrong. Named parameters, and different types for different meanings, are the tools that let the compiler catch a mistake like that.
Core concept: nullable fields, inheritance, mixins and futures working together
Four ideas carry these exercises. Each one is small; the skill lies in how they fit together.
1. Nullable fields say 'unknown', not 'empty'
Animal declares String? sound. null means we do not know a sound; an empty string would claim the animal makes an inaudible one. Callers read it with ?? to supply text such as '...'. Prefer final for such fields so the object stays consistent after construction.
2. Subclasses supply defaults through super
Dog(String name) : super(name, sound: 'Woof') passes the dog's fixed sound up to the Animal constructor. A subclass that passes nothing, like Cat(super.name), inherits the null. Use named parameters for values of the same type: swapping two positional Strings compiles silently, while swapping named arguments does not.
3. Mixins add behaviour without a deeper tree
A mixin is a bundle of members you can add to any compatible class with with. mixin Flyable on Animal says it may only be mixed into subclasses of Animal, which lets its methods use name. A Dog and a Bird both extend Animal, but only Bird adds Flyable, and animal is Flyable checks for that ability at runtime.
4. Futures describe results that arrive later
fetchAnimal returns Future<Animal?>: it may take time, and the answer may be nothing. await unwraps the Future inside an async function. A missing animal is a normal answer, so it is null; an empty key is a programmer error, so it throws an ArgumentError, which appears at the await and is caught with try/on. Future.wait starts several lookups at once and returns the results in the order you listed them, not the order they finished.
| Question | Tool |
|---|---|
| The value might not exist | A nullable type such as String? or Animal? |
| A subclass needs a fixed default | A super(...) call, with named parameters |
| Unrelated classes share behaviour | A mixin, applied with with |
| A result arrives later | Future<T> and await |
| Several results are needed together | Future.wait, results in call order |
- Base class holds the shared fields
- Subclass fixes defaults via super
- Mixin adds an optional ability
- Future delivers an animal, or nothing
- await unwraps it; try/on catches errors
Each layer answers a different question: what do all animals have, what is special about this one, what can only some do, and how long until it arrives.
General pattern
class Base { Base(this.id, {this.note}); final int id; final String? note; }
class Child extends Base { Child(int id) : super(id, note: 'default'); }
mixin Skill on Base {
String act() => 'item $id acts';
}
class Worker extends Base with Skill { Worker(super.id); }
Future<Base?> load(int id) async { /* await something, return a Base or null */ }A base class with a nullable field, a subclass that sets a default through super, a mixin constrained to that base with on, a class that adds it with with, and an async function that returns a nullable result.
Reference solutions: Animal, Dog, Cat, Bird and an async lookup
These solutions cover all four tasks and then add the cases a first draft misses: an animal without a sound (Cat), a lookup that finds nothing ('ghost'), a lookup that fails (an empty key) and several lookups at once. The 40 ms delay in fetchAnimal stands in for a network call. Because every await and every print happens in main, the output is the same on every run.
class Animal {
Animal(this.name, {this.sound});
final String name;
final String? sound; // null means this animal makes no known sound
String makeSound() => '$name says ${sound ?? '...'}';
}
class Dog extends Animal {
Dog(String name) : super(name, sound: 'Woof');
}
class Cat extends Animal {
Cat(super.name); // no sound given, so it stays null
}
mixin Flyable on Animal {
String fly() => '$name takes off';
}
class Bird extends Animal with Flyable {
Bird(String name) : super(name, sound: 'Tweet');
}
final _zoo = <String, Animal>{
'rex': Dog('Rex'),
'tom': Cat('Tom'),
'sky': Bird('Sky'),
};
/// Pretends to call a server. Unknown keys give null; an empty key is a bug.
Future<Animal?> fetchAnimal(String key) async {
await Future<void>.delayed(const Duration(milliseconds: 40));
if (key.isEmpty) throw ArgumentError('key must not be empty');
return _zoo[key.toLowerCase()];
}
Future<void> main() async {
print(Dog('Buddy').makeSound());
print(Cat('Tom').makeSound());
final bird = Bird('Sky');
print(bird.makeSound());
print(bird.fly());
for (final key in ['Rex', 'SKY', 'ghost']) {
final animal = await fetchAnimal(key);
if (animal == null) {
print('$key: no such animal');
} else if (animal is Flyable) {
print('$key: ${animal.makeSound()} / ${animal.fly()}');
} else {
print('$key: ${animal.makeSound()}');
}
}
try {
await fetchAnimal('');
} on ArgumentError catch (e) {
print('caught: ${e.message}');
}
final animals = await Future.wait([
fetchAnimal('tom'),
fetchAnimal('nope'),
fetchAnimal('rex'),
]);
print(animals.map((a) => a?.name ?? 'missing').toList());
}Code breakdown
- Nullable field, named parameter
Animal(this.name, {this.sound});this.name and this.sound copy the arguments into the final fields. The braces make sound a named, optional parameter, so callers write sound: 'Woof' and the meaning of the value is visible at the call site. Leaving it out stores null.
- A fallback for null
String makeSound() => '$name says ${sound ?? '...'}';?? picks '...' when sound is null. The method returns a String instead of printing, so main decides what to do with it.
- Defaults through super
Dog(String name) : super(name, sound: 'Woof');Dog takes only a name and sends its own sound up to the Animal constructor. Cat(super.name) sends no sound, so it stays null and prints Tom says ....
- A constrained mixin
mixin Flyable on Animal {on Animal restricts Flyable to subclasses of Animal and lets fly() use name. Bird adds it with with Flyable, while Dog and Cat do not.
- A nullable future
Future<Animal?> fetchAnimal(String key) async {async makes the function return a Future automatically, so the declared type is Future<Animal?> while the body just returns an Animal? value. The map lookup _zoo[key.toLowerCase()] is null for an unknown key, and that null is passed through as the answer.
- A type check promotes
} else if (animal is Flyable) {By this branch animal is known to be non-null, because the first branch handled null, and is Flyable promotes it to a type that has fly(). No cast is needed. Sky is a Bird, so it flies; Rex and Tom are not Flyable.
- Several lookups at once
final animals = await Future.wait([All three lookups start immediately and take about 40 ms in total instead of 120. The list that comes back follows the order of the input list: Tom, missing, Rex. The null for 'nope' is mapped to 'missing' with ?? afterwards.
Buddy says Woof
Tom says ...
Sky says Tweet
Sky takes off
Rex: Rex says Woof
SKY: Sky says Tweet / Sky takes off
ghost: no such animal
caught: key must not be empty
[Tom, missing, Rex]- main calls fetchAnimal and receives a Future
- main pauses at await; other work may run
- After 40 ms the lookup reads the map
- The Future completes with null
- await hands null back; main prints no such animal
Key found
await returns the Animal
Empty key
ArgumentError reappears at the await
Why a public nullable field is not promoted
After if (sound != null) you would expect sound to be a non-null String. For a public field the compiler refuses, because a subclass, possibly in another library, could override it so that the second read returns something different. The snippet below shows four reliable ways around it: copy the field into a local variable (locals can be promoted), use a switch pattern, use ?. with ??, or make the field private and final, which Dart does promote because nothing outside the library can override it. Each Tag prints four results, one per technique, and they all agree.
class Tag {
Tag(this.text, this._code);
final String? text;
final String? _code; // private + final: the compiler can promote it
int viaLocal() {
final t = text; // copy into a local, and locals can be promoted
return t == null ? 0 : t.length;
}
int viaPattern() => switch (text) {
final String t => t.length,
null => 0,
};
int viaOperator() => text?.length ?? 0;
int viaPrivate() {
if (_code != null) return _code.length;
return 0;
}
}
void main() {
final withText = Tag('hello', 'ab');
final empty = Tag(null, null);
for (final tag in [withText, empty]) {
print([tag.viaLocal(), tag.viaPattern(), tag.viaOperator(), tag.viaPrivate()]);
}
}Futures together or one after another
Awaiting lookups one by one takes the sum of their times; Future.wait takes about as long as the slowest one. The snippet below records the order in which the jobs finish and the order of the results list: the fast job finishes first, yet its result comes second because it was second in the list. If any future inside Future.wait fails, the combined future fails with that error, so decide whether one failure should sink the whole batch. Catching errors inside each job, as the challenge does, keeps the others alive.
final events = <String>[];
Future<String> job(String name, int ms) async {
await Future<void>.delayed(Duration(milliseconds: ms));
events.add('finished $name');
return name;
}
Future<void> main() async {
final results = await Future.wait([job('slow', 120), job('fast', 10)]);
events.forEach(print);
print(results);
}In real projects
In real projects
Flutter code is full of these shapes. A model class has optional fields because JSON from a server may leave them out, and the UI reads them with ?? to show a placeholder. State classes in Flutter often mix in behaviour, for example a State class that adds SingleTickerProviderStateMixin to drive animations, which is exactly with applied to a base class. And almost every screen starts by awaiting a Future from a repository, handling the case where nothing is found and the case where the call fails.
On the server side the same exercise appears as a service that loads a user by id: the result is Future<User?>, the not-found case becomes a 404 response, and invalid input throws an error that a handler turns into a 400. Keeping absent and broken as different things is what makes those responses correct.
Common mistakes
Common mistakes
Swapping arguments of the same type
Dog(String name) : super('Woof', name) compiles when both parameters are Strings, and the dog then says its name. Use named parameters, as in sound: 'Woof', or give each meaning its own type, so the compiler can see the swap.
Forgetting await
Calling makeSound() on the result of fetchAnimal('rex') without await fails with: The method 'makeSound' isn't defined for the type 'Future<Animal?>'. Await first. The same slip on a Future<void> function is worse: it compiles, the work runs in the background, and any error it throws escapes your try block.
Checking a public nullable field and then using it
Writing sound.length after if (sound != null) gives Property 'length' cannot be accessed on 'String?' because it is potentially null, together with a note that 'sound' refers to a public property so it couldn't be promoted. Copy the field into a local variable first.
Using the awaited result without handling null
After await fetchAnimal('ghost') the type is Animal?. Writing animal.name is an error: Property 'name' cannot be accessed on 'Animal?' because it is potentially null. Handle the null branch, use ?., or supply a fallback with ??.
Mixing a constrained mixin into the wrong class
mixin Flyable on Animal cannot be applied with class Robot with Flyable; the compiler says 'Object' doesn't implement 'Animal' so it can't be used with 'Flyable'. Extend Animal first, or remove the on clause if the mixin does not need Animal's members.
Mini challenge
Device inventory: nullable firmware, a mixin and an async report
Write a small device inventory. A Device has an optional firmware version, Phone defaults it to 1.0, and Laptop gets a Rechargeable mixin that keeps the battery between 0 and 100. findDevice answers after a delay, and report looks up a list of ids at the same time and returns one line per id.
- Device has a name and an optional named firmware (String?), and status() reads differently with and without firmware
- Phone takes only a name and passes firmware '1.0' up with super
- Rechargeable is constrained to Device with on, starts the battery at 50 and keeps it within 0..100 in charge() and drain()
- findDevice throws an ArgumentError for a blank id and returns null for an unknown id
- report looks the ids up with Future.wait, one blank id must not sink the whole report, and the lines keep the order of the ids
class Device {
// TODO: final String name and an optional named final String? firmware
// TODO: String status() -> "<name> (firmware <v>)" or "<name> (no firmware)"
}
class Phone extends Device {
// TODO: take only the name and pass firmware '1.0' up with super
}
mixin Rechargeable on Device {
// TODO: int battery starting at 50
// TODO: charge(int) and drain(int), both keeping battery within 0..100
}
class Laptop extends Device with Rechargeable {
// TODO: constructor; status() adds ", battery <n>%" to the inherited text
}
// TODO: a map of known devices: 'p1' -> Phone('Pixel'), 'l1' -> Laptop('ThinkBook')
Future<Device?> findDevice(String id) async {
// TODO: wait about 30 ms, throw ArgumentError for a blank id,
// return the device from the map or null
}
Future<List<String>> report(List<String> ids) async {
// TODO: look the ids up at the same time with Future.wait. One line per id,
// in order: the status, "<id>: not found", or "<blank>: <error message>"
}
Future<void> main() async {
// TODO: charge a Laptop by 70 and drain it by 10 and print its status,
// print a fresh Laptop's status, print each line of
// report(['p1', 'l1', 'zz', ' ']) and finally print report([])
}Expected: Spare (no firmware), battery 90% and Fresh (no firmware), battery 50%, then Pixel (firmware 1.0), ThinkBook (no firmware), battery 50%, zz: not found, <blank>: id must not be blank, and finally [].
Show hint
Cascade notation (..charge(70)..drain(10)) calls several methods on the same object. clamp(0, 100) keeps an int inside a range. For the report, write a small helper that returns one line for one id and catches the ArgumentError inside it, then pass that helper to ids.map(...) and give the result to Future.wait.
Show solution
class Device {
Device(this.name, {this.firmware});
final String name;
final String? firmware;
String status() {
final version = firmware;
return version == null ? '$name (no firmware)' : '$name (firmware $version)';
}
}
class Phone extends Device {
Phone(String name) : super(name, firmware: '1.0');
}
mixin Rechargeable on Device {
int battery = 50;
void charge(int amount) => battery = (battery + amount).clamp(0, 100);
void drain(int amount) => battery = (battery - amount).clamp(0, 100);
}
class Laptop extends Device with Rechargeable {
Laptop(super.name);
@override
String status() => '${super.status()}, battery $battery%';
}
final _inventory = <String, Device>{
'p1': Phone('Pixel'),
'l1': Laptop('ThinkBook'),
};
Future<Device?> findDevice(String id) async {
await Future<void>.delayed(const Duration(milliseconds: 30));
if (id.trim().isEmpty) throw ArgumentError('id must not be blank');
return _inventory[id];
}
Future<String> lineFor(String id) async {
try {
final device = await findDevice(id);
return device?.status() ?? '$id: not found';
} on ArgumentError catch (e) {
return '<blank>: ${e.message}';
}
}
Future<List<String>> report(List<String> ids) => Future.wait(ids.map(lineFor));
Future<void> main() async {
final laptop = Laptop('Spare')
..charge(70)
..drain(10);
print(laptop.status());
print(Laptop('Fresh').status());
for (final line in await report(['p1', 'l1', 'zz', ' '])) {
print(line);
}
print(await report([]));
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A nullable field says unknown; read it with ??, and copy a public field into a local variable to promote it
- Subclasses set defaults through super, and same-typed parameters deserve named parameters
- mixin ... on Base limits where a mixin can be used, and with adds it
- Return Future<T?>, await it, and separate absent (null) from broken (an exception)
- Future.wait returns results in the order given, and one failing future fails the combined one
Dart language overview — Dart