retry method
Retries the future retries times with an exponential backoff delay.
retries specifies the maximum number of retry attempts.
delay determines the base delay for exponential backoff.
retryIf can be used to decide whether to retry for a specific error.
Example:
await (() => apiCall()).retry(retries: 3);
Implementation
Future<T> retry({
int retries = 3,
Duration delay = const Duration(seconds: 1),
bool Function(Object error)? retryIf,
}) async {
var attempts = 0;
while (true) {
try {
return await this();
} catch (e) {
if (attempts >= retries || (retryIf != null && !retryIf(e))) {
rethrow;
}
attempts++;
// Exponential backoff
final delayMillis = delay.inMilliseconds * (1 << (attempts - 1));
await Duration(milliseconds: delayMillis).delayed();
}
}
}