Types, Records, Patterns
These test what Dart 3 changed: sound null safety everywhere, records, pattern matching and sealed class hierarchies. They are also where Flutter-only developers tend to show gaps.
9. Sum the valid integers in a list of strings.
Task: ['4', 'x', '10', '', '-2'] returns 12. Ignore anything that does not parse.
int sumValid(List<String> raw) =>
raw.map(int.tryParse).nonNulls.fold(0, (a, b) => a + b);
int.tryParse returns int?, and nonNulls (Dart 3.0) filters out the nulls and narrows the type to Iterable<int> in one step.
Watch for int.parse inside a try block, which works but uses exceptions for control flow, and for a trailing !, which throws on the first bad value.
10. Return the minimum and maximum of a list in one pass.
Task: minMax([3, -1, 9, 4]) returns (min: -1, max: 9); the caller can read .min and .max.
({int min, int max}) minMax(List<int> xs) {
if (xs.isEmpty) throw ArgumentError('empty list');
var (lo, hi) = (xs.first, xs.first);
for (final x in xs.skip(1)) {
if (x < lo) lo = x;
if (x > hi) hi = x;
}
return (min: lo, max: hi);
}
This question has a trap we hit ourselves while testing.
Our first version returned (int min, int max), a positional record, and result.min failed to compile: per the records documentation, names on positional fields "are purely for documentation".
Named fields, ({int min, int max}), create real getters and can be destructured with final (:min, :max) = minMax(xs);. Records also get value equality for free, which is why the test can compare with ==.
Positional: (int min, int max)
- Fields read as $1 and $2; the names do not compile as getters
- Destructure by position:
final (lo, hi) = r;
Named: ({int min, int max})
- Fields read as .min and .max
- Destructure by name:
final (:min, :max) = r;
11. Compute the area of any shape with an exhaustive switch.
Task: model circles and rectangles so that adding a new shape without handling it is a compile error, not a runtime one.
sealed class Shape {}
class Circle extends Shape {
Circle(this.r);
final double r;
}
class Rect extends Shape {
Rect(this.w, this.h);
final double w, h;
}
double area(Shape s) => switch (s) {
Circle(:final r) => 3.141592653589793 * r * r,
Rect(:final w, :final h) => w * h,
};
A sealed class can only be extended inside its own library, so the compiler knows every subtype and checks that the switch covers them all. Add a Triangle and area stops compiling until it has a case.
The object patterns Circle(:final r) destructure the getters in place. This is the Dart 3 replacement for the visitor pattern, and the class modifiers page covers the other five modifiers candidates should recognize.
12. Validate a JSON object without casts.
Task: accept {'name': 'Ada', 'age': 36} and return 'Ada (36)'. Reject a string age or a negative age with a FormatException.
String describeUser(Object? json) {
if (json case {'name': String name, 'age': int age} when age >= 0) {
return '$name ($age)';
}
throw FormatException('bad user: $json');
}
An if-case with a map pattern checks the keys, the value types and binds the variables in one expression; the when guard adds the range check. Map patterns ignore extra keys, so 'extra': true passes.
The pre-Dart 3 version needed json['age'] as int, which throws a TypeError with a message nobody can act on.
13. Implement an LRU cache.
Task: a cache with a fixed capacity that evicts the least recently used key. get and put must be O(1).
class LruCache<K, V> {
LruCache(this.capacity);
final int capacity;
final _map = LinkedHashMap<K, V>();
V? get(K key) {
final value = _map.remove(key);
if (value != null) _map[key] = value; // move to most recent
return value;
}
void put(K key, V value) {
_map.remove(key);
_map[key] = value;
if (_map.length > capacity) _map.remove(_map.keys.first);
}
}
LinkedHashMap keeps keys in insertion order, so removing and re-inserting a key on access moves it to the end, and the first key is the least recently used.
In Java or C++ this question expects a hash map plus a hand-written linked list; in Dart, knowing the standard library is the answer.
One edge worth raising: this version treats a stored null as a miss, so it only suits non-nullable V.
14. Add a chunked method to every list.
Task: [1, 2, 3, 4, 5].chunked(2) yields [1, 2], [3, 4], [5].
extension Chunked<T> on List<T> {
Iterable<List<T>> chunked(int size) sync* {
if (size <= 0) throw ArgumentError.value(size, 'size');
for (var i = 0; i < length; i += size) {
yield sublist(i, i + size > length ? length : i + size);
}
}
}
An extension adds the method without subclassing List, and the sync* generator yields chunks lazily, so .first on a million-item list builds one chunk, not all of them.
Extensions resolve statically: a list typed as dynamic will not find chunked, a common source of "method not found" errors at runtime. package:collection ships the same idea as slices.
15. Write an immutable value class with equality and copyWith.
Task: two Money(500, 'USD') objects are equal and collapse to one entry in a set.
class Money {
const Money(this.cents, this.currency);
final int cents;
final String currency;
Money copyWith({int? cents, String? currency}) =>
Money(cents ?? this.cents, currency ?? this.currency);
@override
bool operator ==(Object other) =>
other is Money && other.cents == cents && other.currency == currency;
@override
int get hashCode => Object.hash(cents, currency);
}
Overriding == without hashCode is the bug to look for: sets and map keys would then treat equal objects as different. Object.hash combines fields correctly.
The copyWith with nullable parameters has a known limit: it cannot set a nullable field back to null. Teams usually generate all of this with freezed, and a candidate should say so, then show they could write it by hand.
16. Write a generic binary search.
Task: works for any sorted list of comparable values; returns the index or -1.
int binarySearch<T extends Comparable<T>>(List<T> sorted, T target) {
var lo = 0, hi = sorted.length - 1;
while (lo <= hi) {
final mid = lo + ((hi - lo) >> 1);
final c = sorted[mid].compareTo(target);
if (c == 0) return mid;
if (c < 0) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return -1;
}
The bound T extends Comparable<T> lets the function call compareTo on ints, strings or a candidate's own classes.
Computing the midpoint as lo + ((hi - lo) >> 1) is a habit from languages with fixed-width overflow; Dart's native int is 64-bit, but on the web integers are JavaScript numbers, so the habit costs nothing and travels well.