flutter-dio
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNetworking with Dio
使用Dio进行网络开发
- Use Dio as the primary HTTP client package.
- Use type-safe model classes with /
fromJsonfactories for all request/response bodies.toJson - 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)妥善处理所有HTTP状态码。UnauthorizedException - 配置合理的请求超时时间(、
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 into domain-specific
DioExceptiontypes.Failure
- Register interceptors centrally via for consistent behavior across all API calls.
injectable
- 针对横切关注点使用拦截器:
- Auth Interceptor:向请求头附加访问令牌,遇到401状态码时处理令牌刷新逻辑。
- Logging Interceptor:调试模式下通过记录请求/响应日志。
AppLogger - Error Interceptor:将转换为领域特定的
DioException类型。Failure
- 通过统一注册拦截器,确保所有API调用行为一致。
injectable
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的大型响应,使用在后台隔离区解析JSON
compute() - 禁止使用同步网络操作阻塞UI线程
Security
安全规范
- Store tokens via — never in source code or
flutter_secure_storageSharedPreferences - All API communication MUST use HTTPS
- 通过存储令牌,绝对不要存储在源代码或
flutter_secure_storage中SharedPreferences - 所有API通信必须使用HTTPS