timeoutOrNull method

Future<T?> timeoutOrNull(
  1. Duration timeout
)

Returns the result of the future if it completes within timeout, otherwise returns null.

This is a safer alternative to timeout which throws a TimeoutException.

Example:

final result = await apiCall().timeoutOrNull(const Duration(seconds: 5));
if (result == null) {
  // Handle timeout
}

Implementation

Future<T?> timeoutOrNull(Duration timeout) async {
  try {
    return await this.timeout(timeout);
  } on TimeoutException {
    return null;
  }
}