tryCatch method

Future<void> tryCatch(
  1. Future<T> future(), {
  2. T? optimisticResult,
})

Executes the future provided and automatically sets the beacon to the appropriate state.

ie. AsyncLoading while the future is running, AsyncData if the future completes successfully or AsyncError if the future throws an error.

/// Example:

Future<String> fetchUserData() {
  // Imagine this is a network request that might throw an error
  return Future.delayed(Duration(seconds: 1), () => 'User data');
}

await beacon.tryCatch(fetchUserData);

Without tryCatch, handling the potential error requires more boilerplate code:

  beacon.value = AsyncLoading();
  try {
    beacon.value = AsyncData(await fetchUserData());
  } catch (err,stacktrace) {
    beacon.value = AsyncError(err, stacktrace);
  }

Implementation

Future<void> tryCatch(
  Future<T> Function() future, {
  T? optimisticResult,
}) async {
  await AsyncValue.tryCatch(
    future,
    beacon: this,
    optimisticResult: optimisticResult,
  );
}