+1 (415) 480-3939

Typed Error Handling in Flutter with Dart Sealed Classes and Pattern Matching

Most Flutter codebases we audit handle errors the same way: a try/catch in every repository method, a null return meaning "something went wrong", and a snackbar that says "Error". Dart 3 gives us better tools. Sealed classes and pattern matching let the compiler tell you when a failure case is unhandled.

This tutorial builds a small, dependency-free Result type, a sealed failure hierarchy, and a UI mapping that stays in one place.

Step 1: A sealed Result type

sealed class Result<T> {
  const Result();
}

final class Ok<T> extends Result<T> {
  const Ok(this.value);
  final T value;
}

final class Err<T> extends Result<T> {
  const Err(this.failure);
  final Failure failure;
}

Because Result is sealed, every subtype must live in the same library, so the compiler knows the full set of cases.

Step 2: A sealed failure hierarchy

Model the failures your product actually distinguishes, not every exception type.

sealed class Failure {
  const Failure();
}

final class NoConnection extends Failure { const NoConnection(); }
final class Unauthorized extends Failure { const Unauthorized(); }
final class NotFound extends Failure { const NotFound(); }
final class Validation extends Failure {
  const Validation(this.fieldErrors);
  final Map<String, String> fieldErrors;
}
final class Unexpected extends Failure {
  const Unexpected(this.error, this.stackTrace);
  final Object error;
  final StackTrace stackTrace;
}

Step 3: Convert exceptions at the boundary

Catch exceptions once, in the data layer, and return a Result. Nothing above the repository should need try/catch.

Future<Result<User>> fetchUser(String id) async {
  try {
    final res = await _dio.get('/users/$id');
    return Ok(User.fromJson(res.data as Map<String, dynamic>));
  } on DioException catch (e, st) {
    return Err(switch (e.response?.statusCode) {
      401 || 403 => const Unauthorized(),
      404 => const NotFound(),
      422 => Validation(_fieldErrors(e.response?.data)),
      null => const NoConnection(),
      _ => Unexpected(e, st),
    });
  } catch (e, st) {
    return Err(Unexpected(e, st));
  }
}

Note that a null status code is not always a lost connection (a timeout or TLS error also lands there). Check e.type if you need to tell them apart.

Step 4: Exhaustive handling with switch expressions

String messageFor(Failure f) => switch (f) {
  NoConnection() => 'You appear to be offline. Try again.',
  Unauthorized() => 'Please sign in again.',
  NotFound() => 'We could not find that item.',
  Validation(:final fieldErrors) => fieldErrors.values.first,
  Unexpected() => 'Something went wrong on our side.',
};

Add a new Failure subtype and every switch without a default stops compiling until you handle it. That is the whole point: avoid default: and _ => on sealed types.

Step 5: Use it in the UI

final result = await repo.fetchUser(id);
switch (result) {
  case Ok(:final value):
    setState(() => _user = value);
  case Err(:final failure):
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text(messageFor(failure))));
}

If you use async gaps like this, check context.mounted before touching context after the await.

Step 6: Combine with state management

With Riverpod, an AsyncNotifier can hold Result or you can let AsyncValue carry the failure. Pick one. A pattern that works well: repositories return Result, and the notifier translates Err into AsyncError(failure, st), so widgets use AsyncValue.when and a single messageFor.

Step 7: Log what matters

Only Unexpected should go to crash reporting. NoConnection and Unauthorized are normal operating conditions; reporting them drowns real bugs.

if (failure case Unexpected(:final error, :final stackTrace)) {
  crashReporter.record(error, stackTrace);
}

Step 8: Test the mapping

Because errors are plain values, tests need no mocks of exception flow:

test('404 maps to NotFound', () async {
  final repo = UserRepository(fakeDioReturning(404));
  final r = await repo.fetchUser('1');
  expect(r, isA<Err<User>>());
  expect((r as Err<User>).failure, isA<NotFound>());
});

Pitfalls

  • Too many failure types. If the UI treats two failures identically, merge them.
  • Swallowing stack traces. Always keep them on Unexpected.
  • Mixing styles. Half the repositories throwing and half returning Result is worse than either. Migrate one feature at a time, starting at the data layer.
  • Default branches. They silently defeat exhaustiveness checking.

Wrap-up

A sealed Result, a small failure hierarchy and one messageFor function give you predictable error behavior and compiler-enforced coverage. If your team is untangling error handling in a larger Flutter codebase, our consultants can help with an architecture review.