onRequest method

  1. @override
Future<void> onRequest(
  1. RequestOptions options,
  2. RequestInterceptorHandler handler
)

Called when the request is about to be sent.

Implementation

@override
Future<void> onRequest(
  RequestOptions options,
  RequestInterceptorHandler handler,
) async {
  final customConnectTimeout = options.extra['connectTimeout'];
  if (customConnectTimeout is Duration) {
    options.connectTimeout = customConnectTimeout;
  }

  final bool offlineSync = options.extra['offlineSync'] ?? true;
  final bool isSyncRequest = options.extra['isSyncRequest'] ?? false;
  final String serverUrl = options.uri.toString();

  // If the system is currently marked offline for non-sync requests:
  // Run an instant probe to verify if the server/internet has recovered.
  if (!isSyncRequest &&
      offlineSync &&
      !LikeConnectivityManager().hasConnection) {
    final check = await LikeConnectivityManager().checkServerReachability(
      serverUrl,
      force: true,
    );

    // If probe confirms it is STILL offline, fail fast immediately (0ms delay).
    // This skips wasting network retries and long timeouts!
    if (!check.isOnline) {
      options.extra[_preflightOfflineKey] = true;
      return handler.reject(
        DioException(
          requestOptions: options,
          error: 'No internet connection',
          type: DioExceptionType.connectionError,
        ),
      );
    }
  }

  return handler.next(options);
}