init method

Future<void> init({
  1. required String baseUrl,
  2. bool needToShowLog = false,
  3. bool needToLogRequests = false,
  4. NetworkMonitoringFunction? networkMonitoringFunction,
  5. int? unauthorizedStatusCode = 401,
  6. void onUnauthorizedCallBack()?,
})

Must be called once before using request. Example:

ApiService.instance.init(baseUrl: "https://api.example.com");

Implementation

Future<void> init({
  required String baseUrl,
  bool needToShowLog = false,
  bool needToLogRequests = false,
  // unauthorized callback
  NetworkMonitoringFunction? networkMonitoringFunction,
  int? unauthorizedStatusCode = 401,
  void Function()? onUnauthorizedCallBack,
}) async {
  _dio = Dio(
    BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: const Duration(milliseconds: 30000),
      receiveTimeout: const Duration(milliseconds: 30000),
      sendTimeout: const Duration(milliseconds: 30000),
    ),
  );

  this.networkMonitoringFunction = networkMonitoringFunction;

  // Handle cookie from server
  if (!kIsWeb) {
    // In mobile device
    Directory dir = await getApplicationSupportDirectory();
    final cookiePath = '${dir.path}/cookies';

    _cookieJar = PersistCookieJar(storage: FileStorage(cookiePath));

    if (_cookieJar != null) {
      _dio.interceptors.add(CookieManager(_cookieJar!));
    }
  } else {
    // In web PWA
    // Cookies are handled by the browser on web.
    // !IMPORTANT: You should use `withCredentials` in web when needed.
    // Example:
    // options: Options(
    //   extra: {if (kIsWeb) 'withCredentials': true},
    // ),
    _cookieJar = CookieJar();
  }

  if (needToLogRequests) {
    if (!Get.isRegistered<DebugLogController>()) {
      Get.put(DebugLogController(), permanent: true);
    }
    _dio.interceptors.add(DebugInterceptor());
  }

  if (needToShowLog) {
    _dio.interceptors.add(
      dio.LogInterceptor(
        requestHeader: true,
        responseHeader: true,
        requestBody: true,
        responseBody: true,
      ),
    );
  }

  _dio.interceptors.add(
    InterceptorsWrapper(
      onRequest: (options, handler) {
        return handler.next(options);
      },
      onResponse: (response, handler) {
        return handler.next(response);
      },
      onError: (DioException e, handler) {
        final statusCode = e.response?.statusCode;

        // handle specific status code
        if (statusCode != null && statusCode == unauthorizedStatusCode) {
          onUnauthorizedCallBack?.call();
        }
        return handler.next(e);
      },
    ),
  );
}