initNet method

Future<void> initNet({
  1. required String baseUrl,
  2. NetworkAdapter? adapter,
  3. String? cachePath,
  4. String cacheName = 'network_cache',
  5. String databaseName = 'rxnet_cache.db',
  6. CacheMode baseCacheMode = CacheMode.ONLY_REQUEST,
  7. List<AdapterInterceptor>? interceptors,
  8. BaseOptions? baseOptions,
  9. bool systemLog = false,
  10. bool isDebug = kDebugMode,
  11. CheckNetWork? baseCheckNet,
  12. List<String>? ignoreCacheKeys,
  13. Map<String, dynamic>? baseUrlEnv,
  14. int cacheInvalidationTime = 365 * 24 * 60 * 60 * 1000,
  15. double debugWindowWidth = 800,
  16. double debugWindowHeight = 600,
})

Implementation

Future<void> initNet({
  required String baseUrl,
  NetworkAdapter? adapter,
  String? cachePath,
  String cacheName = 'network_cache',
  String databaseName = 'rxnet_cache.db',
  CacheMode baseCacheMode = CacheMode.ONLY_REQUEST,
  List<AdapterInterceptor>? interceptors,
  BaseOptions? baseOptions,
  bool systemLog = false,
  bool isDebug = kDebugMode,
  CheckNetWork? baseCheckNet,
  List<String>? ignoreCacheKeys,
  Map<String, dynamic>? baseUrlEnv,
  int cacheInvalidationTime = 365 * 24 * 60 * 60 * 1000,
  double debugWindowWidth = 800,
  double debugWindowHeight = 600
}) async {
  LogUtil.init(systemLog: systemLog,debug: isDebug);

  // 存储 baseUrl
  this._baseUrl = baseUrl;
  this._baseCheckNet = baseCheckNet;
  this._baseCacheMode = baseCacheMode;
  this._cacheInvalidationTime = cacheInvalidationTime;
  this._baseIgnoreCacheKeys = ignoreCacheKeys;
  debugWindow = ValueNotifier(Size(debugWindowWidth, debugWindowHeight));

  // 如果提供了自定义适配器,使用它;否则使用默认的 DioAdapter
  // If custom adapter provided, use it; otherwise use default DioAdapter
  if (adapter != null) {
    _adapter = adapter;
  } else if (_adapter == null) {
    // 只在 _adapter 为 null 时创建默认适配器
    // Only create default adapter when _adapter is null
    final options = baseOptions ?? BaseOptions(
      contentType: Headers.jsonContentType,
    );
    _adapter = DioAdapter.withOptions(options);
  }

  // 如果是 DioAdapter,配置 Dio 选项
  if (_adapter is DioAdapter) {
    final dioAdapter = _adapter as DioAdapter;

    if (baseOptions != null) {
      dioAdapter.dio.options = baseOptions;
    }

    dioAdapter.dio.options.baseUrl = baseUrl;
  }

  // 如果是 HttpAdapter,baseUrl 将在请求构建时处理
  // If HttpAdapter, baseUrl will be handled during request building

  // 添加适配器拦截器(适用于所有适配器)
  if (interceptors != null && interceptors.isNotEmpty) {
    for (var interceptor in interceptors) {
      _adapter?.addInterceptor(interceptor);
    }
  }

  if (baseUrlEnv != null && baseUrlEnv.isNotEmpty) {
    _baseUrlEnv.addAll(baseUrlEnv);
  }

  _database = RxNetDataBase();
  await RxNetDataBase.initDatabase(
    databasePath: cachePath,
    databaseName: databaseName,
    cacheName: cacheName,
  );
}