Result<T, E extends Object> class sealed

A type-safe alternative to throwing exceptions, inspired by Rust's Result<T, E>.

Result represents one of two states:

  • Ok — success, wrapping a value of type T.
  • Err — failure, wrapping an error of type E.

Because Result is a sealed class, exhaustive pattern matching with switch is available (Dart 3.0+):

final result = fetchUser(id);
switch (result) {
  case Ok(value: final user): print('Got $user');
  case Err(error: final e):  print('Failed: $e');
}

T is the success value type; E must extend Object (including Exception, String, or custom error classes).

Implementers

Constructors

Result.err(E error)
Creates a failed Result wrapping error.
const
factory
Result.ok(T value)
Creates a successful Result wrapping value.
const
factory

Properties

errOrNull → E?
Returns the error value if this is Err, otherwise null.
no setter
hashCode → int
The hash code for this object.
no setterinherited
isErr → bool
Whether this is an Err result.
no setter
isOk → bool
Whether this is an Ok result.
no setter
okOrNull → T?
Returns the success value if this is Ok, otherwise null.
no setter
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited

Methods

fold<R>(R onOk(T value), R onErr(E error)) → R
Collapses the result with onOk or onErr, producing a single value of type R.
map<R>(R f(T value)) → Result<R, E>
Transforms the success value with f if this is Ok.
mapErr<F extends Object>(F f(E error)) → Result<T, F>
Transforms the error value with f if this is Err.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
orElse<F extends Object>(Result<T, F> f(E error)) → Result<T, F>
Returns the success value if this is Ok, otherwise the result of calling f on the error.
toString() → String
A string representation of this object.
override
unwrap() → T
Returns the success value, or throws a ResultException if this is Err.
unwrapOr(T defaultValue) → T
Returns the success value if this is Ok, otherwise returns defaultValue.
unwrapOrElse(T onErr(E error)) → T
Returns the success value if this is Ok, otherwise computes a fallback using onErr.

Operators

operator ==(Object other) → bool
The equality operator.
inherited