retry<T> static method
Retries a function with exponential backoff
Example:
final result = await Helpers.retry(
() => apiCall(),
maxAttempts: 3,
delay: Duration(seconds: 1),
);
Implementation
static Future<T> retry<T>(
Future<T> Function() action, {
int maxAttempts = 3,
Duration delay = const Duration(seconds: 1),
bool Function(Object)? onError,
}) async {
int attempts = 0;
while (attempts < maxAttempts) {
try {
return await action();
} catch (e) {
attempts++;
if (attempts >= maxAttempts) rethrow;
if (onError != null && !onError(e)) rethrow;
await Future.delayed(delay * attempts); // Exponential backoff
}
}
throw Exception('Max retry attempts reached');
}