networking
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
- 使用拦截器处理横切关注点:
- 认证拦截器:在请求头中附加访问令牌,遇到401状态码时处理令牌刷新。
- 日志拦截器:调试模式下通过记录请求/响应日志。
AppLogger - 错误拦截器:将转换为领域特定的
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负责协调远程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的大型响应,使用在后台隔离区解析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