Skip to main content

Sealed Class to Handle Success and Error in Dart

With the release of Dart 3.0, sealed classes were introduced. This new feature enables us to effortlessly create our own Result type using just a few lines of code.

sealed class Result<S> {}

final class Success<S> extends Result<S> {
  final S value;

final class Failure<S> extends Result<S> {
  final Exception exception;

Then you can use it like this

final result = await getCurrencyRate('SGD');
final rateValue = switch (result) {
  Success(value: final rate) => rate.toString(),
  Failure(exception: final exception) => 'Error: $exception',

By continuing to use the site, you agree to the use of cookies.