safeCall<R> method
Wraps an ApiCallResponse-producing call with busy state and error handling.
call: the async function performing the API call.onSuccess: maps the decodedjsonBodyinto the target typeR; if omitted, returnsnullon success.errorTitle/errorMessage: shown via AlertManager.showDanger on non-2xx responses or exceptions whenshowErrorAlertistrue.showErrorAlert: set tofalseto suppress the alert and let the caller handle errors.manageBusy: set tofalseif 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);
}
}