res 1.5.0 copy "res: ^1.5.0" to clipboard
res: ^1.5.0 copied to clipboard

Result class that stops errors from throwing by returning either a value or an error

Result class like many other but this one can return void type too, and does not need a "Unit" type

Features #

  • Prevent app crashes

Usage #

Wrap a function that can throw an error: #

Result.of(
  () {
    final n = Random().nextInt(10);

    if (n < 5) {
      throw RangeError(n);
    }

    return n;
  },
  error: (e, s) => e.toString(),
);

Or wrap a future that can throw an error: #

Result.ofFuture(
  functionThatCanThrowError(),
  error: (e, s) => e.toString(),
);

Or catch error manually #

Future<int> functionThatCanThrowError() async {
  final n = Random().nextInt(10);

  if (n < 5) {
    throw RangeError(n);
  }

  return n;
}

Future<Result<int, String>> functionThatDoesNotThrow() async {
  try {
    return Result.ok(await functionThatCanThrowError());
  } catch (e, s) {
    return Result.err(e.toString() + s.toString());
  }
}

void main() async {
  final result = await functionThatDoesNotThrow();

  if (result.isError) {
    return print('Error');
  }

  return print(result.value);
}
2
likes
0
points
982
downloads

Publisher

verified publishermuha.dev

Weekly Downloads

Result class that stops errors from throwing by returning either a value or an error

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

flutter, meta

More

Packages that depend on res