networking

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.
  • 使用拦截器处理横切关注点:
    • 认证拦截器:在请求头中附加访问令牌,遇到401状态码时处理令牌刷新。
    • 日志拦截器:调试模式下通过
      AppLogger
      记录请求/响应日志。
    • 错误拦截器:将
      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负责协调远程DataSources和本地缓存,处理网络数据

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