when<TResult extends Object?> method

  1. @optionalTypeArgs
TResult when<TResult extends Object?>({
  1. required TResult success(
    1. Success value
    ),
  2. required TResult failure(
    1. Failure error
    ),
})
inherited

This is the primary way to work with the value and error in a Result. Provide a success function which will process the value when the Result was successful, and a failure function which will process the error when the Result is a failure.

Process both success and failure with different logic:

final result = fetchPerson(12);
result.when(
  success: (value) => state = MyState.personFound(value);
  failure: (error) => state = MyState.error(error);
);

Or create a common type from both cases by returning the same type and capturing the return value of when.

final result = fetchPerson(12);
final description = result.when(
  success: (value) => 'Found Person ${person.id}';
  failure: (error) => 'Problem finding a person.';
);

Or use Nothing to trigger success processing even when there is no meaningful value.

final Result<Nothing, DatabaseError> result = await vacuumDatabase();
result.when(
  success: (_) => _notify('All clean!');
  failure: (error) {
    _log(error);
    _recoverFromBackup();
  },
);

Implementation

@optionalTypeArgs
TResult when<TResult extends Object?>({
  required TResult Function(Success value) success,
  required TResult Function(Failure error) failure,
}) {
  // Actual implementation in the _Success and _Failure
  // subclasses. It is the exact implementation originally
  // generated by Freezed.
  throw _privateConstructorUsedError;
}