blocCatch method

Future<void> blocCatch({
  1. required Future<void> actions(),
  2. bool? isLoading = true,
  3. dynamic onError(
    1. dynamic
    )?,
})

Executes a given asynchronous action within a try-catch block, handling loading states.

This method provides a convenient way to perform asynchronous operations while automatically managing loading states and error handling.

Parameters:

  • actions: A required function that contains the asynchronous operations to be performed.
  • isLoading: An optional boolean that determines whether to show/hide loading indicators. Defaults to true.

Usage:

await blocCatch(
  actions: () async {
    // Perform some asynchronous operations
    await fetchData();
    await processData();
  },
  isLoading: true, // Optional, defaults to true
);

The method will:

  1. Show a loading indicator if isLoading is true.
  2. Execute the provided actions.
  3. Hide the loading indicator after actions complete or if an error occurs.
  4. Log any errors that occur during execution.

Note: This method uses showLoading and hideLoading internally, which should be implemented in the concrete Bloc class or a mixin.

Implementation

Future<void> blocCatch({
  required Future<void> Function() actions,
  bool? isLoading = true,
  Function(dynamic)? onError,
}) async {
  try {
    if (isLoading!) {
      showLoading();
    }
    await actions.call();
    if (isLoading) {
      hideLoading();
    }
  } catch (e) {
    if (isLoading!) {
      hideLoading();
    }
    if (onError != null) {
      onError(e);
    } else {
      developer.log('$e', name: 'Error');
    }
  }
}