safeCall<R> method

Future<R?> safeCall<R>({
  1. required Future<ApiCallResponse> call(),
  2. R onSuccess(
    1. dynamic data
    )?,
  3. String errorTitle = 'Errore',
  4. String? errorMessage,
  5. bool showErrorAlert = true,
  6. bool manageBusy = true,
})

Wraps an ApiCallResponse-producing call with busy state and error handling.

  • call: the async function performing the API call.
  • onSuccess: maps the decoded jsonBody into the target type R; if omitted, returns null on success.
  • errorTitle / errorMessage: shown via AlertManager.showDanger on non-2xx responses or exceptions when showErrorAlert is true.
  • showErrorAlert: set to false to suppress the alert and let the caller handle errors.
  • manageBusy: set to false if the caller already manages busy state.

Implementation

Future<R?> safeCall<R>({
  required Future<ApiCallResponse> Function() call,
  R Function(dynamic data)? onSuccess,
  String errorTitle = 'Errore',
  String? errorMessage,
  bool showErrorAlert = true,
  bool manageBusy = true,
}) async {
  if (manageBusy) setBusy(true);
  try {
    final response = await call();
    if (response.succeeded) {
      return onSuccess?.call(response.jsonBody);
    }
    if (showErrorAlert) {
      final msg = errorMessage ??
          response.error?.message ??
          'Operazione non riuscita (${response.statusCode})';
      AlertManager.showDanger(errorTitle, msg);
    }
    return null;
  } catch (e) {
    if (showErrorAlert) {
      AlertManager.showDanger(errorTitle, errorMessage ?? e.toString());
    }
    return null;
  } finally {
    if (manageBusy) setBusy(false);
  }
}