Common pitfalls

suggest change

Dart is a forgiving language with a sound type system and null safety, but some mistakes still compile fine and only show up at runtime, or behave differently than you'd expect coming from Java, JavaScript or C#. This article collects the ones that cause the most bugs, shows what goes wrong, and how to fix it.

Most of these can be caught by the analyzer. The last section shows which lints to turn on.

Forgetting to await a Future

Calling an async function without await starts it, but your code doesn't wait for it to finish. The analyzer doesn't complain by default:

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

void main() async {
  saveUser('alice'); // no await
  print('done');
}
done
saved alice

Worse, errors from a Future nobody awaits are not caught by the surrounding try/catch:

Future<void> fails() async {
  throw StateError('boom');
}

void main() async {
  try {
    fails(); // missing await
  } catch (e) {
    print('caught: $e'); // never runs
  }
  print('after try');
}
after try
Unhandled exception:
Bad state: boom
#0      fails (file:///.../main.dart:2:3)
...

The try block finishes before the Future completes, so the error escapes and becomes an unhandled exception that terminates the program. Adding await fixes both problems:

  try {
    await fails();
  } catch (e) {
    print('caught: $e');
  }
caught: Bad state: boom
after try

If you really want "fire and forget", say so explicitly with unawaited() from dart:async, and handle errors inside the function. See Async and Await for more.

forEach with an async callback doesn't wait

Iterable.forEach calls the callback and ignores its return value. When the callback is async, the returned Futures are simply dropped:

Future<void> process(int n) async {
  await Future.delayed(Duration(milliseconds: 100 * n));
  print('processed $n');
}

void main() async {
  [3, 1, 2].forEach((n) async {
    await process(n);
  });
  print('done');
}
done
processed 1
processed 2
processed 3

done is printed first, and the items finish in order of their delay, not in list order. Use a for loop to process items one after another:

  for (final n in [3, 1, 2]) {
    await process(n);
  }
  print('done');
processed 3
processed 1
processed 2
done

Or use Future.wait to run them concurrently and wait for all of them:

  await Future.wait([3, 1, 2].map(process));
  print('done');
processed 1
processed 2
processed 3
done

The same applies to map with an async callback: it produces an Iterable<Future> that does nothing until you pass it to Future.wait.

async functions returning void

An async function declared as void can't be awaited by its callers, and its errors go straight to the zone's unhandled error handler:

// Bad: callers can't wait for it or catch its errors
void saveSettings() async {
  await writeFile();
}

// Good
Future<void> saveSettings() async {
  await writeFile();
}

With the void version, await saveSettings(); is a compile-time error ("This expression has a type of 'void' so its value can't be used"), so callers have no way to know when saving has finished. Always return Future<void> from async functions. The only common exception is a callback whose required signature returns void, such as an event handler.

/ always returns a double

In Dart, / is floating-point division even when both operands are integers. Use ~/ for integer division:

void main() {
  print(7 / 2);   // 3.5
  print(6 / 2);   // 3.0
  print(7 ~/ 2);  // 3

  final items = 10;
  final perPage = 3;
  // int pages = items / perPage; // error: double can't be assigned to int
  final pages = (items + perPage - 1) ~/ perPage;
  print(pages);   // 4
}
3.5
3.0
3
4

Also watch out for negative numbers. ~/ truncates toward zero, while % is a Euclidean modulo whose result is never negative. Use remainder() if you want the sign of the dividend, like % in C or Java:

void main() {
  print((-7) ~/ 2);           // -3
  print((-7) % 2);            // 1
  print((-7).remainder(2));   // -1
}
-3
1
-1

Floating-point precision

double is an IEEE 754 64-bit floating-point number, so most decimal fractions can't be represented exactly:

void main() {
  print(0.1 + 0.2);         // 0.30000000000000004
  print(0.1 + 0.2 == 0.3);  // false

  // compare with a tolerance
  print(((0.1 + 0.2) - 0.3).abs() < 1e-9); // true

  // format for display
  print((0.1 + 0.2).toStringAsFixed(2));   // 0.30
}
0.30000000000000004
false
true
0.30

Never store money as double. Store whole cents in an int, or use a decimal package such as package:decimal.

Integer overflow and the web

On the Dart VM and in native executables, int is a 64-bit signed integer that silently wraps around on overflow:

void main() {
  const max = 9223372036854775807;
  print(max + 1); // -9223372036854775808

  final big = BigInt.from(max) + BigInt.one;
  print(big);     // 9223372036854775808
}
-9223372036854775808
9223372036854775808

When compiled to JavaScript, int is a JavaScript number: integers are only exact up to 2^53, and 6 / 2 prints as 3 instead of 3.0. If your code runs on both platforms, use BigInt for large values such as 64-bit IDs, or keep them as strings.

Empty literals are dynamic, and {} is a Map

Without a type, an empty list literal is a List<dynamic>, which accepts anything and turns off type checking for its elements:

void main() {
  var names = [];      // List<dynamic>
  names.add('alice');
  names.add(42);       // no error
  print(names);        // [alice, 42]

  var typed = <String>[];
  // typed.add(42);    // compile-time error
}

An even more surprising one: {} is an empty Map, not an empty Set:

void main() {
  var a = {};          // Map<dynamic, dynamic>
  var b = <String>{};  // Set<String>
  var c = {'x'};       // Set<String>, because it has a non-key/value element
  print(a is Map);     // true
  print(b is Set);     // true
  print(c is Set);     // true
}
true
true
true

Always give empty collection literals a type argument, or declare the variable type: final ids = <int>{}; or final Set<int> ids = {};.

Casting decoded JSON

jsonDecode returns dynamic, and the lists and maps inside it are always List<dynamic> and Map<String, dynamic>. Assigning one to a more specific type compiles (because the source is dynamic) but fails at runtime:

import 'dart:convert';

void main() {
  final data = jsonDecode('{"ids": [1, 2, 3]}');
  try {
    List<int> ids = data['ids'];
    print(ids);
  } catch (e) {
    print(e);
  }
}
type 'List<dynamic>' is not a subtype of type 'List<int>'

The list contains only integers, but its runtime type is List<dynamic>, and a List<dynamic> is not a List<int>. Convert it instead of casting it:

  final ids = (data['ids'] as List).cast<int>();   // lazy view, checks on access
  final ids2 = List<int>.from(data['ids']);         // new list, checks now
  final ids3 = [for (final x in data['ids']) x as int];

dynamic also hides typos: data.lenght compiles and throws NoSuchMethodError at runtime. Give decoded values a type as early as possible, ideally by parsing them into classes. See JSON and Pattern matching for safe ways to destructure JSON.

Generic lists are covariant

Dart lets you assign a List<int> to a List<Object> variable. Reading is safe, but adding an element of the wrong type fails at runtime:

void addDefault(List<Object> items) {
  items.add('default');
}

void main() {
  final numbers = <int>[1, 2];
  try {
    addDefault(numbers); // compiles
  } on TypeError {
    print('TypeError: a List<int> can\'t hold a String');
  }
}
TypeError: a List<int> can't hold a String

The object is still a List<int> at runtime, and the VM checks every add. If a function needs to add arbitrary objects, make it create and return a new list, or make it generic: void addAll<T>(List<T> items, T value).

Lazy iterables

map, where, expand, skip, take and friends don't produce a new list. They return a lazy Iterable that runs your callback every time it's iterated, and not at all if it's never iterated:

void main() {
  var calls = 0;
  final squares = [1, 2, 3].map((n) {
    calls++;
    return n * n;
  });
  print('calls after map: $calls');

  print(squares.toList());
  print(squares.toList());
  print('calls after two iterations: $calls');

  [1, 2, 3].map(print); // prints nothing: the result is never iterated
}
calls after map: 0
[1, 4, 9]
[1, 4, 9]
calls after two iterations: 6

This causes two kinds of bugs: side effects in map that never happen, and expensive callbacks (or ones that create new objects) running again on each iteration. Call .toList() once if you need the results more than once, and use a for loop for side effects.

Modifying a list while iterating over it

Adding to or removing from a collection inside a for-in loop over that same collection throws:

void main() {
  final numbers = [1, 2, 3, 4];
  try {
    for (final n in numbers) {
      if (n.isEven) numbers.remove(n);
    }
  } on ConcurrentModificationError {
    print('ConcurrentModificationError');
  }

  final nums = [1, 2, 3, 4];
  nums.removeWhere((n) => n.isEven);
  print(nums); // [1, 3]
}
ConcurrentModificationError
[1, 3]

Use removeWhere / retainWhere, build a new list with where(...).toList(), or iterate over a copy: for (final n in [...numbers]).

List.filled shares one object

List.filled(n, value) puts the same object in every slot. With a mutable value, such as a list, changing one element changes all of them:

void main() {
  final grid = List.filled(3, <int>[]);
  grid[0].add(1);
  print(grid); // [[1], [1], [1]]

  final fixed = List.generate(3, (_) => <int>[]);
  fixed[0].add(1);
  print(fixed); // [[1], [], []]
}
[[1], [1], [1]]
[[1], [], []]

List.filled also creates a fixed-length list by default, so add throws Unsupported operation: Cannot add to a fixed-length list. Pass growable: true if you need to add elements later. List.generate is growable by default.

final is not immutable, const is

final means the variable can't be reassigned. The object it refers to can still be changed:

void main() {
  final list = [1, 2];
  list.add(3);         // fine
  print(list);         // [1, 2, 3]
  // list = [];        // compile-time error

  const frozen = [1, 2];
  try {
    frozen.add(3);     // compiles, but throws at runtime
  } on UnsupportedError catch (e) {
    print(e);
  }
}
[1, 2, 3]
Unsupported operation: Cannot add to an unmodifiable list

const collections, List.unmodifiable() and UnmodifiableListView all throw at runtime when you try to modify them, because their static type is still List. See Constants for more on const.

Overriding == without hashCode

Set, Map keys and HashSet use hashCode first and == second. If you override == but not hashCode, equal objects end up in different hash buckets:

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

  @override
  bool operator ==(Object other) =>
      other is Point && other.x == x && other.y == y;
  // missing: hashCode
}

void main() {
  print(Point(1, 2) == Point(1, 2));     // true
  final points = {Point(1, 2), Point(1, 2)};
  print(points.length);                  // 2
  print(points.contains(Point(1, 2)));   // false
}
true
2
false

Always override both together: int get hashCode => Object.hash(x, y);. Or use a record, which has value equality built in: (x: 1, y: 2) == (x: 1, y: 2) is true.

A related surprise is that collections don't compare by content: [1, 2] == [1, 2] is false. Use ListEquality or DeepCollectionEquality from package:collection. Both are covered in Equality and comparison.

Methods that accept Object?

contains, remove, indexOf and the [] operator on Map take Object?, so passing a value of the wrong type compiles and silently never matches:

void main() {
  final ids = <int>[1, 2, 42];
  final input = '42';             // e.g. read from a query string

  print(ids.contains(input));     // false
  print(ids.contains(int.parse(input))); // true

  final ages = {'alice': 30};
  print(ages[1]);                 // null
}
false
true
null

The collection_methods_unrelated_type lint (enabled in the recommended lint set) catches these.

sort() sorts in place and returns void

List.sort() modifies the list and returns nothing, so print(names.sort()) is a compile-time error. And strings are compared character by character, which is wrong for numbers stored as strings:

void main() {
  final versions = ['10', '9', '100', '2'];
  versions.sort();
  print(versions); // [10, 100, 2, 9]

  versions.sort((a, b) => int.parse(a).compareTo(int.parse(b)));
  print(versions); // [2, 9, 10, 100]

  // sorted copy, original unchanged
  final original = [3, 1, 2];
  final sorted = [...original]..sort();
  print('$original $sorted'); // [3, 1, 2] [1, 2, 3]
}
[10, 100, 2, 9]
[2, 9, 10, 100]
[3, 1, 2] [1, 2, 3]

Note the cascade ..sort(): it calls sort and evaluates to the list itself, not to the void result. See Sorting.

Fields don't get type promotion

Null checks promote local variables, but not public fields or getters, because a getter could return a different value the second time:

class User {
  String? nickname;

  void greet() {
    if (nickname != null) {
      // print(nickname.length); // error: 'nickname' is a public field
      //                        //  so it can't be promoted
    }

    // fix: copy to a local variable
    final nick = nickname;
    if (nick != null) {
      print('Hi $nick (${nick.length} chars)');
    }
  }
}

void main() {
  User()
    ..nickname = 'kj'
    ..greet();
}
Hi kj (2 chars)

Since Dart 3.2, private final fields (like final String? _nickname) are promoted. For everything else, copy to a local or use a pattern: if (nickname case final nick?) { ... }.

Resist the urge to "fix" it with nickname!.length. The ! operator throws Null check operator used on a null value if you're wrong, and it hides the bug until runtime. See Null safety.

late moves errors to runtime

late tells the compiler "trust me, this will be initialized before it's used". If you're wrong, you get an exception instead of a compile error:

class Service {
  late String endpoint;

  void fetch() => print('fetching $endpoint');
}

void main() {
  try {
    Service().fetch();
  } catch (e) {
    print(e);
  }
}
LateInitializationError: Field 'endpoint' has not been initialized.

Also remember that a late variable with an initializer is lazy: late final config = loadConfig(); runs loadConfig() the first time config is read, not when the object is created. That's useful, but surprising if loadConfig() has side effects or can throw. Prefer constructor parameters or a nullable type when initialization can genuinely be missing.

Closures and loop variables

In a for loop, each iteration gets a fresh copy of the loop variable, so closures capture the value you expect (unlike var in JavaScript). But a variable declared outside the loop is shared by all closures:

void main() {
  final a = <void Function()>[];
  for (var i = 0; i < 3; i++) {
    a.add(() => print('for: $i'));
  }
  for (final f in a) f();

  final b = <void Function()>[];
  var j = 0;
  while (j < 3) {
    b.add(() => print('while: $j'));
    j++;
  }
  for (final f in b) f();
}
for: 0
for: 1
for: 2
while: 3
while: 3
while: 3

Copy the value into a local variable inside the loop body (final current = j;) if the closure should keep the current value.

String length is not the number of characters

String.length counts UTF-16 code units. Emoji and many other characters outside the Basic Multilingual Plane take two code units, and some visible characters are made of several code points:

import 'package:characters/characters.dart';

void main() {
  const thumbs = '👍🏽';               // thumbs up + skin tone modifier
  print(thumbs.length);              // 4 UTF-16 code units
  print(thumbs.runes.length);        // 2 code points
  print(thumbs.characters.length);   // 1 user-perceived character

  const name = 'Zoë 😀';
  print(name.substring(0, 5));       // 'Zoë ' + half of the emoji
  print(name.characters.take(5));    // Zoë 😀
}
4
2
1
Zoë �
Zoë 😀

Use package:characters when you truncate, reverse or count text that users see. See Unicode and encodings.

Listening to a single-subscription stream twice

Most streams, including those from async* functions, files and HTTP responses, can only be listened to once:

Stream<int> countTo(int n) async* {
  for (var i = 1; i <= n; i++) {
    yield i;
  }
}

void main() async {
  final numbers = countTo(3);
  print(await numbers.toList());
  try {
    print(await numbers.length);
  } on StateError catch (e) {
    print(e);
  }
}
[1, 2, 3]
Bad state: Stream has already been listened to.

Collect the values once with toList() and reuse the list, call the generator function again to get a new stream, or convert it with asBroadcastStream() when several listeners need the same events.

Let the analyzer catch them

Many of the mistakes above are detected by lints. Start from package:lints/recommended.yaml (or package:flutter_lints) and add stricter checks in analysis_options.yaml:

include: package:lints/recommended.yaml

analyzer:
  language:
    strict-casts: true      # no implicit casts from dynamic
    strict-inference: true  # warn when a type is inferred as dynamic
    strict-raw-types: true  # warn on List instead of List<int>

linter:
  rules:
    - unawaited_futures     # missing await in async functions
    - discarded_futures     # Futures dropped in non-async code
    - avoid_void_async      # async functions that return void
    - avoid_dynamic_calls   # method calls on dynamic values
    - hash_and_equals       # == without hashCode
    - only_throw_errors

With strict-casts enabled, List<int> ids = data['ids']; from the JSON example becomes a compile-time error instead of a runtime crash. Run dart analyze locally and in CI (see Testing in CI) so these problems never reach production.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents