Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 61 ยท Real-World Dart

Common Dart Mistakes and Pitfalls

Avoid the Dart bugs that trip up almost everyone: overusing the ! operator, forgetting await, forEach with async, list equality, const lists and shared fills.

Dart is designed to catch many mistakes before the program runs, but a handful of traps survive: code that compiles, looks fine, and still does the wrong thing. They tend to fall into the same few families, which is good news, because once you have met each one you will spot it in your own code and in code reviews.

This lesson walks through the most common ones with a short explanation of why it happens and a fix. The Dart snippets are read-only. Dart is not installed on the site, so the TypeScript stand-ins reproduce the same behaviour (reference equality, un-awaited work, frozen lists) so you can run it yourself.

Mistake 1: silencing null safety with !

The ! operator says "trust me, this is not null". If you are wrong, the program throws at run time, which is exactly the crash null safety was meant to prevent.

DART
String? findUser(Map<int, String> users, int id) => users[id];

void main() {
  final users = {1: 'Ada'};
  final name = findUser(users, 2)!;   // throws: Null check operator used on a null value
  print(name.toUpperCase());
}

Prefer to handle the missing case where it can happen:

DART
void main() {
  final users = {1: 'Ada'};
  final name = findUser(users, 2) ?? 'unknown';       // a default
  print(name.toUpperCase());

  final user = findUser(users, 1);
  if (user == null) {
    print('No such user');
    return;
  }
  print(user.length);                                  // promoted to String
}

Use ! only when something outside the type system guarantees the value, and say why in a comment. A ! you cannot justify is a bug waiting for the right input. The same goes for late fields you forget to initialize and for as casts: they are promises, and a broken promise is an exception. See null safety basics and late variables.

TypeScript The cost of a forced non-null (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Mistake 2: forgetting await

An async function returns a Future immediately. If you call it and ignore the result, the rest of your code runs before the work is done, and any error it throws is never seen by you.

DART
Future<void> save(String data) async {
  await Future.delayed(const Duration(milliseconds: 100));
  print('saved $data');
}

Future<void> main() async {
  save('profile');            // forgotten await
  print('done');              // prints first!
}
TEXT
done
saved profile

The analyzer helps. The unawaited_futures lint flags a call whose Future is dropped. If you really want fire-and-forget, say so with unawaited(save('profile')) from dart:async, which also documents your intent. Remember too that a Future which fails and is never awaited or given an error handler reports an unhandled error that can crash a server. For the mechanics, see futures and async/await.

A closely related trap is forEach with an async callback. forEach ignores what the callback returns, so it never waits:

DART
Future<void> main() async {
  final names = ['a', 'b', 'c'];

  names.forEach((name) async {     // does NOT wait for each call
    await save(name);
  });
  print('after forEach');          // prints before any "saved"

  for (final name in names) {      // waits for each in order
    await save(name);
  }
  print('after loop');
}

Use a plain for loop to run steps one after another, or await Future.wait(names.map(save)) to run them at the same time.

sequenceDiagram
    participant M as main
    participant S as save()
    M->>S: save("profile") without await
    M->>M: print("done")
    S-->>M: finishes later

Without await, main moves on while save is still working.

TypeScript Forgotten await and forEach (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Mistake 3: expecting == to compare contents

For most classes, == is identity: two objects are equal only if they are the very same object. Lists, sets and maps work the same way.

DART
void main() {
  print([1, 2] == [1, 2]);                 // false
  print(const [1, 2] == const [1, 2]);     // true: canonicalized constants are one object
  print({'a': 1} == {'a': 1});             // false
  print((1, 2) == (1, 2));                 // true: records compare by value
}

For your own classes, override == and hashCode together, or equal objects will behave strangely in a Set or as Map keys:

DART
class Point {
  const Point(this.x, this.y);
  final int x, y;

  @override
  bool operator ==(Object other) =>
      other is Point && other.x == x && other.y == y;

  @override
  int get hashCode => Object.hash(x, y);
}

To compare collections by content use ListEquality, SetEquality or DeepCollectionEquality from package:collection, or in Flutter listEquals. Records and (since Dart 3) simple value classes written as records avoid the problem entirely. See operator overloading, == and hashCode.

TypeScript Identity versus value equality (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Mistake 4: confusing const, final and mutability

const means the object is a compile-time constant and is deeply unmodifiable. final only means the variable cannot be reassigned. Mixing them up leads to two opposite surprises.

DART
void main() {
  final names = ['Ada'];
  names.add('Linus');                 // fine: the list is mutable, the variable is final
  // names = [];                      // error: final variable can only be set once

  const fixed = ['Ada'];
  fixed.add('Linus');                 // compiles, throws UnsupportedError at run time
}

The second line compiles because a const list still has the add method. It only fails when it runs: "Cannot add to an unmodifiable list". Danger zones: const [] as a default value that you later try to modify, and lists returned by List.unmodifiable or toList(growable: false). If a function needs a list it may change, create a fresh [...source] or List.of(source).

A third variation is List.filled, which repeats one object:

DART
void main() {
  final grid = List.filled(3, <int>[]);   // three references to the SAME list
  grid[0].add(1);
  print(grid);                            // [[1], [1], [1]]

  final fixedGrid = List.generate(3, (_) => <int>[]);
  fixedGrid[0].add(1);
  print(fixedGrid);                       // [[1], [], []]
}
TypeScript Frozen lists and shared fills (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Mistake 5: catching too much

catch (e) with no on clause catches everything, including Error subclasses such as StateError, TypeError and AssertionError, which signal bugs in your code. Swallowing them hides the bug.

DART
try {
  doWork();
} catch (e) {            // too broad: hides programming errors
  print('failed');
}

try {
  doWork();
} on FormatException catch (e) {      // catches exactly what you expect
  print('bad input: ${e.message}');
}

Catch the specific exception you can actually handle, and let everything else travel up to a place that logs it. Also avoid using exceptions for ordinary control flow, such as parsing with int.parse inside a try when int.tryParse returns null instead. More in exceptions and error handling.

Smaller traps worth knowing

  • var items = []; is a List<dynamic>. Write final items = <String>[]; to keep type safety.
  • / always returns a double. Use ~/ for integer division: 7 / 2 is 3.5, 7 ~/ 2 is 3.
  • Changing a list while looping over it throws ConcurrentModificationError. Loop over a copy or use removeWhere.
  • Comparing doubles with ==. 0.1 + 0.2 == 0.3 is false; compare with a tolerance.
  • dynamic switches off checking. Use Object? when you truly do not know the type, then test it with is or a pattern, as in the type system.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does await omission do in save('x'); print('done'); when save is async?

    Calling an async function without await lets the caller continue immediately. The analyzer lint unawaited_futures warns about it.
  2. 2. Why does names.forEach((n) async { await save(n); }); not wait?

    forEach discards the callback's return value, so it never waits for the Futures. Use a for loop with await, or Future.wait.
  3. 3. What is the result of [1, 2] == [1, 2] in Dart?

    Lists use identity equality. Use ListEquality from package:collection to compare contents. Records, by contrast, compare by value.
  4. 4. What happens at run time with const fixed = ['a']; fixed.add('b');?

    A const list is deeply unmodifiable, but the add method still exists, so the code compiles and throws when it runs.
  5. 5. What is wrong with List.filled(3, <int>[])?

    List.filled repeats a single object. Use List.generate with a callback to create a new inner list per slot.

Summary

  • Treat !, as and late as promises you must be able to justify; prefer ??, null checks and promotion.
  • Always await (or deliberately unawaited) a Future; never pass an async callback to forEach.
  • == on lists, sets, maps and most classes compares identity; override == and hashCode together, or use records and collection-equality helpers.
  • final fixes the variable, const fixes the whole object; List.filled shares one element.
  • Catch specific exceptions with on, and keep Errors visible.

Next: Project: Todo Command-Line App.