flutter-dio

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Networking with Dio

使用Dio进行网络开发

  • Use Dio as the primary HTTP client package.
  • Use type-safe model classes with
    fromJson
    /
    toJson
    factories for all request/response bodies.
  • Handle all HTTP status codes appropriately with typed exceptions (e.g.,
    ServerException
    ,
    NetworkException
    ,
    UnauthorizedException
    ).
  • Use proper request timeouts (
    connectTimeout
    ,
    receiveTimeout
    ,
    sendTimeout
    ).
  • 采用Dio作为核心HTTP客户端包。
  • 所有请求/响应体均使用带有
    fromJson
    /
    toJson
    工厂方法的类型安全模型类。
  • 通过类型化异常(如
    ServerException
    NetworkException
    UnauthorizedException
    )妥善处理所有HTTP状态码。
  • 配置合理的请求超时时间(
    connectTimeout
    receiveTimeout
    sendTimeout
    )。

Dio Interceptors

Dio拦截器

  • Use interceptors for cross-cutting concerns:
    • Auth Interceptor: Attach access tokens to headers, handle token refresh on 401.
    • Logging Interceptor: Log requests/responses in debug mode via
      AppLogger
      .
    • Error Interceptor: Transform
      DioException
      into domain-specific
      Failure
      types.
  • Register interceptors centrally via
    injectable
    for consistent behavior across all API calls.
  • 针对横切关注点使用拦截器:
    • Auth Interceptor:向请求头附加访问令牌,遇到401状态码时处理令牌刷新逻辑。
    • Logging Interceptor:调试模式下通过
      AppLogger
      记录请求/响应日志。
    • Error Interceptor:将
      DioException
      转换为领域特定的
      Failure
      类型。
  • 通过
    injectable
    统一注册拦截器,确保所有API调用行为一致。

Repository Pattern

仓库模式

  • DataSources contain only raw Dio API calls — no business logic or mapping
  • Repositories orchestrate between remote DataSources and local cache for network data
  • 数据源(DataSources)仅包含原生Dio API调用,不包含业务逻辑或数据映射逻辑
  • 仓库(Repositories)负责协调远程数据源和本地缓存,处理网络数据

Retry & Resilience

重试与弹性设计

  • Implement retry logic with exponential backoff for transient failures (e.g., 500, timeout).
  • Set a maximum retry count (default: 3 retries).
  • Cache responses when appropriate to reduce network calls and improve offline UX.
  • 针对瞬时故障(如500错误、超时)实现指数退避重试逻辑。
  • 设置最大重试次数(默认:3次重试)。
  • 合适场景下缓存响应结果,减少网络调用,优化离线用户体验。

Performance

性能优化

  • Parse JSON in background isolates for large responses (> 1MB) using
    compute()
  • Do NOT block the UI thread with synchronous network operations
  • 针对大于1MB的大型响应,使用
    compute()
    在后台隔离区解析JSON
  • 禁止使用同步网络操作阻塞UI线程

Security

安全规范

  • Store tokens via
    flutter_secure_storage
    — never in source code or
    SharedPreferences
  • All API communication MUST use HTTPS
  • 通过
    flutter_secure_storage
    存储令牌,绝对不要存储在源代码或
    SharedPreferences
  • 所有API通信必须使用HTTPS