TExcelTAD
Home › Dart › Dart Exercises

Dart Exercises

Practice makes the syntax stick. Each exercise below has a starter program that compiles and runs but doesn't solve the task yet. Edit it in the playground, press ▶ Run, and compare with the expected result. Try on your own before opening the solution!

# Exercise Topics
1 Receipt formatter strings, numbers, interpolation
2 FizzBuzz, the Dart way loops, switch expressions, records
3 Safe average null safety, iterables
4 Word frequency maps, sorting
5 Inventory filter collection if/for, records
6 Shapes with sealed classes sealed classes, patterns
7 Bank account classes, getters, exceptions
8 Extension helpers extension methods, generics
9 Async order pipeline async/await, Future.wait
10 Event stream summary streams, async*

1. Receipt formatter

Print each line as name padded to 10 characters, then the price with two decimals, then a total line.

dart · try it yourself
void main() {
  final items = {'Coffee': 2.5, 'Bagel': 3.25, 'Juice': 4.0};
  // TODO: print "Coffee     2.50" etc., then "TOTAL      9.75"
  print(items);
}
{Coffee: 2.5, Bagel: 3.25, Juice: 4.0}
Show solution
dart
void main() {
  final items = {'Coffee': 2.5, 'Bagel': 3.25, 'Juice': 4.0};
  var total = 0.0;
  for (final MapEntry(key: name, value: price) in items.entries) {
    print('${name.padRight(10)} ${price.toStringAsFixed(2)}');
    total += price;
  }
  print('${'TOTAL'.padRight(10)} ${total.toStringAsFixed(2)}');
}

Output:

text
Coffee     2.50
Bagel      3.25
Juice      4.00
TOTAL      9.75

2. FizzBuzz, the Dart way

For 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for both, otherwise the number. Use a switch expression on a record (n % 3, n % 5).

dart · try it yourself
String fizz(int n) {
  // TODO: switch on (n % 3, n % 5)
  return '$n';
}

void main() {
  print([for (var n = 1; n <= 15; n++) fizz(n)].join(' '));
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
dart
String fizz(int n) => switch ((n % 3, n % 5)) {
      (0, 0) => 'FizzBuzz',
      (0, _) => 'Fizz',
      (_, 0) => 'Buzz',
      _ => '$n',
    };

void main() {
  print([for (var n = 1; n <= 15; n++) fizz(n)].join(' '));
}

Output:

text
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

3. Safe average

Some sensor readings are null. Write average so it ignores nulls and returns null when there are no real values.

dart · try it yourself
double? average(List<double?> readings) {
  // TODO: ignore nulls; return null if nothing is left
  return 0;
}

void main() {
  print(average([20.5, null, 22.5, null, 21.0]));
  print(average([null, null]));
  print(average([]));
}
0.0
0.0
0.0
Show solution
dart
double? average(List<double?> readings) {
  final values = readings.nonNulls; // or: whereType<double>()
  if (values.isEmpty) return null;
  return values.reduce((a, b) => a + b) / values.length;
}

Output:

text
21.333333333333332
null
null

4. Word frequency

Count how often each word appears (case-insensitive, ignore punctuation) and print the top 3 as word: count, most frequent first. Break ties alphabetically.

dart · try it yourself
void main() {
  const text = 'The cat saw the dog. The dog saw a bird, and the bird flew!';
  // TODO: count words, then print the top 3
  print(text.split(' ').length);
}
14
Show solution
dart
void main() {
  const text = 'The cat saw the dog. The dog saw a bird, and the bird flew!';
  final counts = <String, int>{};
  for (final w in text.toLowerCase().split(RegExp(r'[^a-z]+'))) {
    if (w.isEmpty) continue;
    counts[w] = (counts[w] ?? 0) + 1;
  }
  final top = counts.entries.toList()
    ..sort((a, b) {
      final byCount = b.value.compareTo(a.value);
      return byCount != 0 ? byCount : a.key.compareTo(b.key);
    });
  for (final e in top.take(3)) {
    print('${e.key}: ${e.value}');
  }
}

Output:

text
the: 4
bird: 2
dog: 2

5. Inventory filter

Build a list of strings with a collection for and collection if: one line per product that is in stock, plus a final 'LOW STOCK' warning line only if any in-stock product has fewer than 5 units.

dart · try it yourself
void main() {
  final products = [
    (name: 'Pen', qty: 40),
    (name: 'Ink', qty: 0),
    (name: 'Pad', qty: 3),
  ];
  // TODO: build the report with collection for/if
  final report = <String>[];
  print(report);
}
[]
Show solution
dart
void main() {
  final products = [
    (name: 'Pen', qty: 40),
    (name: 'Ink', qty: 0),
    (name: 'Pad', qty: 3),
  ];
  final report = [
    for (final p in products)
      if (p.qty > 0) '${p.name} x${p.qty}',
    if (products.any((p) => p.qty > 0 && p.qty < 5)) 'LOW STOCK',
  ];
  print(report);
}

Output:

text
[Pen x40, Pad x3, LOW STOCK]

6. Shapes with sealed classes

Complete area with an exhaustive switch expression. Add a Triangle(base, height) subclass too.

dart · try it yourself
sealed class Shape {}

class Circle extends Shape {
  final double r;
  Circle(this.r);
}

class Square extends Shape {
  final double side;
  Square(this.side);
}

double area(Shape s) => switch (s) {
      Circle(:final r) => 3.14159 * r * r,
      Square() => 0, // TODO
    };

void main() {
  for (final s in [Circle(1), Square(3)]) {
    print(area(s).toStringAsFixed(2));
  }
}
3.14
0.00
Show solution
dart
sealed class Shape {}

class Circle extends Shape {
  final double r;
  Circle(this.r);
}

class Square extends Shape {
  final double side;
  Square(this.side);
}

class Triangle extends Shape {
  final double base, height;
  Triangle(this.base, this.height);
}

double area(Shape s) => switch (s) {
      Circle(:final r) => 3.14159 * r * r,
      Square(:final side) => side * side,
      Triangle(:final base, :final height) => base * height / 2,
    };

void main() {
  for (final s in [Circle(1), Square(3), Triangle(4, 5)]) {
    print(area(s).toStringAsFixed(2));
  }
}

Output:

text
3.14
9.00
10.00

7. Bank account

Make balance read-only from outside, reject non-positive deposits with an ArgumentError, and throw a StateError when withdrawing more than the balance.

dart · try it yourself
class Account {
  int balance = 0; // TODO: make private + add a getter

  void deposit(int amount) {
    balance += amount; // TODO: validate
  }

  void withdraw(int amount) {
    balance -= amount; // TODO: validate
  }
}

void main() {
  final acc = Account()..deposit(100);
  for (final action in [() => acc.withdraw(30), () => acc.deposit(-5), () => acc.withdraw(500)]) {
    try {
      action();
      print('ok, balance ${acc.balance}');
    } catch (e) {
      print('rejected: $e');
    }
  }
}
ok, balance 70
ok, balance 65
ok, balance -435
Show solution
dart
class Account {
  int _balance = 0;
  int get balance => _balance;

  void deposit(int amount) {
    if (amount <= 0) throw ArgumentError.value(amount, 'amount', 'must be positive');
    _balance += amount;
  }

  void withdraw(int amount) {
    if (amount > _balance) throw StateError('insufficient funds');
    _balance -= amount;
  }
}

Output:

text
ok, balance 70
rejected: Invalid argument (amount): must be positive: -5
rejected: Bad state: insufficient funds

8. Extension helpers

Write an extension on Iterable<T> with a chunked(int size) method returning List<List<T>>, and an extension on String with isPalindrome (ignoring case and spaces).

dart · try it yourself
extension Chunks<T> on Iterable<T> {
  List<List<T>> chunked(int size) => [toList()]; // TODO
}

extension Palindrome on String {
  bool get isPalindrome => false; // TODO
}

void main() {
  print([1, 2, 3, 4, 5].chunked(2));
  print('Never odd or even'.isPalindrome);
  print('Dart'.isPalindrome);
}
[[1, 2, 3, 4, 5]]
false
false
Show solution
dart
extension Chunks<T> on Iterable<T> {
  List<List<T>> chunked(int size) {
    final list = toList();
    return [
      for (var i = 0; i < list.length; i += size)
        list.sublist(i, i + size > list.length ? list.length : i + size),
    ];
  }
}

extension Palindrome on String {
  bool get isPalindrome {
    final clean = toLowerCase().replaceAll(' ', '');
    return clean == clean.split('').reversed.join();
  }
}

Output:

text
[[1, 2], [3, 4], [5]]
true
false

9. Async order pipeline

fetchPrice takes 30 ms per call. Compute the total of three items concurrently (not one after another) and print it.

dart · try it yourself
Future<int> fetchPrice(String item) async {
  await Future.delayed(Duration(milliseconds: 30));
  return {'tea': 20, 'cake': 35, 'soup': 50}[item] ?? 0;
}

Future<void> main() async {
  final items = ['tea', 'cake', 'soup'];
  var total = 0;
  for (final item in items) {
    total += await fetchPrice(item); // TODO: run concurrently
  }
  print('total: $total');
}
total: 105
Show solution
dart
Future<void> main() async {
  final items = ['tea', 'cake', 'soup'];
  final prices = await Future.wait(items.map(fetchPrice));
  final total = prices.fold<int>(0, (a, b) => a + b);
  print('total: $total');
}

Output (same total, but ~30 ms instead of ~90 ms):

text
total: 105

10. Event stream summary

Write an async* function levels that yields the readings [3, 7, 12, 5, 15] one by one, then consume it with await for and print each value that is above 6, followed by the maximum.

dart · try it yourself
Stream<int> levels() async* {
  // TODO: yield the readings
}

Future<void> main() async {
  await for (final l in levels()) {
    print(l);
  }
  print('done');
}
done
Show solution
dart
Stream<int> levels() async* {
  for (final r in [3, 7, 12, 5, 15]) {
    await Future.delayed(Duration(milliseconds: 1));
    yield r;
  }
}

Future<void> main() async {
  var maxLevel = 0;
  await for (final l in levels()) {
    if (l > 6) print('high: $l');
    if (l > maxLevel) maxLevel = l;
  }
  print('max: $maxLevel');
}

Output:

text
high: 7
high: 12
high: 15
max: 15

Test yourself

Which method drops null elements from an Iterable<T?>, returning Iterable<T>?

  1. removeNulls()
  2. nonNulls
  3. compact()
  4. whereNotNull()

In exercise 9, why is Future.wait(items.map(fetchPrice)) faster than awaiting in a loop?

  1. It uses isolates
  2. All three requests start before any is awaited, so they wait concurrently
  3. It caches results
  4. It skips the delay