retryFuture<T> function

Future<T> retryFuture<T>(
  1. Future<T> factory(), {
  2. int times = 3,
  3. Duration delay = Duration.zero,
})

Retries factory up to times additional times on failure. An optional delay is awaited between attempts.

Because a Future cannot be "replayed" once created, this top-level function accepts a factory that creates a new Future on each attempt.

final result = await retryFuture(() => fetchData(), times: 3,
    delay: Duration(seconds: 1));

Implementation

Future<T> retryFuture<T>(
  Future<T> Function() factory, {
  int times = 3,
  Duration delay = Duration.zero,
}) async {
  var attempts = 0;
  while (true) {
    try {
      return await factory();
    } catch (e) {
      if (attempts >= times) rethrow;
      attempts++;
      if (delay > Duration.zero) await Future<void>.delayed(delay);
    }
  }
}