retry<T> function
Call fn
retrying so long as retryIf
return true
for the exception
thrown, up-to maxAttempts
times.
Defaults to 8 attempts, sleeping as following after 1st, 2nd, 3rd, ..., 7th attempt:
- 400 ms +/- 25%
- 800 ms +/- 25%
- 1600 ms +/- 25%
- 3200 ms +/- 25%
- 6400 ms +/- 25%
- 12800 ms +/- 25%
- 25600 ms +/- 25%
final response = await retry(
// Make a GET request
() => http.get('https://google.com').timeout(Duration(seconds: 5)),
// Retry on SocketException or TimeoutException
retryIf: (e) => e is SocketException || e is TimeoutException,
);
print(response.body);
If no retryIf
function is given this will retry any for any Exception
thrown. To retry on an Error, the error must be caught and rethrown
as an Exception.
Implementation
Future<T> retry<T>(
FutureOr<T> Function() fn, {
Duration delayFactor = const Duration(milliseconds: 200),
double randomizationFactor = 0.25,
Duration maxDelay = const Duration(seconds: 30),
int maxAttempts = 8,
FutureOr<bool> Function(Exception)? retryIf,
FutureOr<void> Function(Exception)? onRetry,
}) =>
RetryOptions(
delayFactor: delayFactor,
randomizationFactor: randomizationFactor,
maxDelay: maxDelay,
maxAttempts: maxAttempts,
).retry(fn, retryIf: retryIf, onRetry: onRetry);