withTimeout<T> function

Future<T> withTimeout<T>(
  1. Future<T> fn(),
  2. Duration timeout, {
  3. T? fallback,
})

Runs fn with timeout; on timeout returns fallback or rethrows.

Implementation

Future<T> withTimeout<T>(Future<T> Function() fn, Duration timeout, {T? fallback}) async {
  try {
    return await fn().timeout(timeout);
  } on TimeoutException catch (e) {
    if (fallback != null) return fallback;
    developer.log('Timeout after $timeout', name: 'withTimeout', error: e);
    rethrow;
  }
}