RxNet class

RxNet Plus - Flutter 网络请求库 / Flutter Network Request Library

author: zhengzaihong email: 1096877329@qq.com date: 2025-08-12

============================================================================ 版本历史 / Version History

📦 Version 0.6.0 (2026-04-23) - 适配器架构重构 / Adapter Architecture Refactoring

🎯 核心变更 / Core Changes:

  1. 可插拔适配器架构 / Pluggable Adapter Architecture

    • 引入 NetworkAdapter 接口,支持多种 HTTP 客户端库
    • Introduced NetworkAdapter interface, supporting multiple HTTP client libraries
    • 三种内置适配器:DioAdapter(默认)、HttpAdapter(轻量级)、MockAdapter(测试)
    • Three built-in adapters: DioAdapter (default), HttpAdapter (lightweight), MockAdapter (testing)
    • 支持自定义适配器实现
    • Support for custom adapter implementations
  2. 统一的拦截器系统 / Unified Interceptor System

    • AdapterInterceptor 接口,与具体网络库解耦
    • AdapterInterceptor interface, decoupled from specific network libraries
    • 拦截器可在不同适配器间复用
    • Interceptors can be reused across different adapters
    • RxNetLogAdapterInterceptor 替代 RxNetLogInterceptor
    • RxNetLogAdapterInterceptor replaces RxNetLogInterceptor
  3. 改进的取消令牌 / Improved Cancel Token

    • 新的 CancelToken 类,独立于 Dio
    • New CancelToken class, independent of Dio
    • 支持回调通知和状态查询
    • Support for callback notifications and status queries
  4. 枚举类型优化 / Enum Type Optimization

    • HttpMethod 和 ResponseType 使用大写枚举值
    • HttpMethod and ResponseType use uppercase enum values
    • 更符合 Dart 3.0+ 规范
    • More compliant with Dart 3.0+ specifications

🔄 迁移指南 / Migration Guide: 详见 MIGRATION_GUIDE_0.6.0.md See MIGRATION_GUIDE_0.6.0.md for details

💡 使用示例 / Usage Examples:

// 1. 使用默认适配器(DioAdapter)
// Using default adapter (DioAdapter)
await RxNet.init(
  baseUrl: "https://api.example.com",
  interceptors: [RxNetLogAdapterInterceptor()],
);

// 2. 使用轻量级适配器(HttpAdapter)
// Using lightweight adapter (HttpAdapter)
final api = RxNet.create();
await api.initNet(
  baseUrl: "https://api.example.com",
  adapter: HttpAdapter(),
);

// 3. 使用测试适配器(MockAdapter)
// Using test adapter (MockAdapter)
final mockAdapter = MockAdapter();
mockAdapter.setMockResponse('/api/user', mockResponse);
await api.initNet(adapter: mockAdapter);

============================================================================ 📦 Version 0.5.0 (2025-10-03) - API 优化 / API Optimization

🎯 核心变更 / Core Changes:

  1. 参数类型明确化 / Explicit Parameter Types

    • setPathParam() - RESTful 路径参数 / RESTful path parameters
    • setQueryParam() - URL 查询参数 / URL query parameters
    • setBodyParam() - 请求体参数 / Request body parameters
  2. RESTful 自动检测 / RESTful Auto-Detection

    • 自动识别路径中的 {placeholder}
    • Automatically recognize {placeholder} in paths
    • 无需手动调用 setRestfulUrl(true)
    • No need to manually call setRestfulUrl(true)
  3. 请求体类型清晰化 / Clear Request Body Types

    • asJson() - JSON 格式 / JSON format
    • asFormData() - FormData 格式 / FormData format
    • asUrlEncoded() - URL 编码格式 / URL-encoded format

💡 使用示例 / Usage Examples:

// RESTful 请求 / RESTful request
await RxNet.get()
  .setPath("/api/users/{id}/posts")
  .setPathParam("id", "123")
  .setQueryParam("page", 1)
  .request();

// POST JSON 数据 / POST JSON data
await RxNet.post()
  .setPath("/api/user")
  .setBodyParams({"name": "John", "age": 25})
  .asJson()
  .request();

// 文件上传 / File upload
await RxNet.post()
  .setPath("/api/upload")
  .setBodyParam("file", multipartFile)
  .asFormData()
  .request();

🔄 迁移指南 / Migration Guide: 详见 MIGRATION_GUIDE_0.5.0.md 或 迁移指南_0.5.0.md See MIGRATION_GUIDE_0.5.0.md or 迁移指南_0.5.0.md

============================================================================ 📦 Version 0.4.3 及之前 / Version 0.4.3 and Earlier

🎯 核心特性 / Core Features:

  1. 多实例支持 / Multi-Instance Support (0.4.0+)

    • 支持创建多个 RxNet 实例
    • Support for creating multiple RxNet instances
    • 适用于多场景(业务 API、日志 API 等)
    • Suitable for multiple scenarios (business API, logging API, etc.)
  2. 缓存策略 / Cache Strategy

    • 支持多种缓存模式
    • Support for multiple cache modes
    • async/await 和回调方式都支持缓存
    • Both async/await and callback methods support caching
  3. 基础 API / Basic API

    • setParam() - 设置参数 / Set parameter
    • setParams() - 批量设置参数 / Set multiple parameters
    • setRestfulUrl(true) - 启用 RESTful / Enable RESTful

💡 使用示例 / Usage Examples (0.4.3 API - 仍然支持 / Still Supported):

// 基础请求 / Basic request
await RxNet.get()
  .setPath("api/weather")
  .setParam("city", "101030100")
  .setRestfulUrl(true)
  .request();

// POST 请求 / POST request
await RxNet.post()
  .setPath("/api/user")
  .setParams({"name": "John", "age": 25})
  .toBodyData()
  .request();

============================================================================ 📚 更多文档 / More Documentation

  • API 文档 / API Documentation: README.md
  • 迁移指南 / Migration Guides: MIGRATION_GUIDE_*.md
  • 更新日志 / Changelog: CHANGELOG.md
  • 示例代码 / Examples: example/lib/

============================================================================

Properties

adapter NetworkAdapter?
no setter
baseUrl String
no setter
cacheManager ↔ CacheManager
latefinal
debugManager DebugManager
latefinal
hashCode int
The hash code for this object.
no setterinherited
logManager ↔ LogManager
latefinal
logsNotifier ValueNotifier<List<String>>
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

cacheLogToFile(String filePath) → void
将日志输出到文件
deleteRequest<T>() BuildRequest<T>
getAdapter() NetworkAdapter?
getBaseCacheMode() CacheMode?
getCacheInvalidationTime() int
getCheckNetWork() CheckNetWork?
getClient() Dio?
getHeaders() Map<String, dynamic>
getIgnoreCacheKeys() List<String>?
getRequest<T>() BuildRequest<T>
headRequest<T>() BuildRequest<T>
initNet({required String baseUrl, NetworkAdapter? adapter, Directory? cacheDir, String cacheName = 'app_local_data', CacheMode baseCacheMode = CacheMode.ONLY_REQUEST, List<AdapterInterceptor>? interceptors, BaseOptions? baseOptions, bool systemLog = false, bool isDebug = kDebugMode, CheckNetWork? baseCheckNet, List<String>? ignoreCacheKeys, HiveCipher? encryptionCipher, Map<String, dynamic>? baseUrlEnv, int cacheInvalidationTime = 365 * 24 * 60 * 60 * 1000, double debugWindowWidth = 800, double debugWindowHeight = 600}) Future<void>
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
optionsRequest<T>() BuildRequest<T>
patchRequest<T>() BuildRequest<T>
postRequest<T>() BuildRequest<T>
putRequest<T>() BuildRequest<T>
setCollectLogs(bool collect) → void
setEnv(String env) → void
setHeaders(Map<String, dynamic> header) → void
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited

Static Properties

debugWindow ValueNotifier<Size>
getter/setter pair
I RxNet
final

Static Methods

create() RxNet
delete<T>({String path = ""}) BuildRequest
get<T>({String path = ""}) BuildRequest
getDefaultAdapter() NetworkAdapter?
getDefaultClient() Dio?
getGlobalHeaders() Map<String, dynamic>
init({required String baseUrl, NetworkAdapter? adapter, Directory? cacheDir, String cacheName = 'app_local_data', CacheMode baseCacheMode = CacheMode.ONLY_REQUEST, List<AdapterInterceptor>? interceptors, BaseOptions? baseOptions, bool systemLog = false, CheckNetWork? baseCheckNet, List<String>? ignoreCacheKeys, HiveCipher? encryptionCipher, Map<String, dynamic>? baseUrlEnv, int cacheInvalidationTime = 365 * 24 * 60 * 60 * 1000, double debugWindowWidth = 800, double debugWindowHeight = 600}) Future<void>
中文: baseUrl:服务端基础地址 cacheDir:缓存目录 cacheName:缓存文件 baseCacheMode:缓存策略 interceptors:自定义的拦截器 systemLog:是否使用系统自带的打印 baseCheckNet:网络检测,外部自行实现,网络不通不发起请求 ignoreCacheKeys:网络检测,外部自行实现 encryptionCipher:数据加密,不传默认即可 baseUrlEnv:多环境的基础服务地址 cacheInvalidationTime:缓存时效:默认1年 debugWindowWidth:调试窗口默认宽 debugWindowHeight:调试窗口默认高
options<T>({String path = ""}) BuildRequest
patch<T>({String path = ""}) BuildRequest
post<T>({String path = ""}) BuildRequest
put<T>({String path = ""}) BuildRequest
readCache(String key) Future
saveCache(String key, dynamic value) → void
setDefaultEnv(String env) → void
setGlobalHeaders(Map<String, dynamic> header) → void
showDebugWindow(BuildContext context) → void