Flutter 网络请求指南:从 iOS 到 Flutter 的 Dio + Retrofit 组合
引言
作为一名 iOS 开发者转向 Flutter,你可能会对网络请求的处理方式感到困惑。在 iOS 中,我们习惯使用 URLSession
或 Alamofire
,而在 Flutter 中,我们有了更强大的组合:Dio + Retrofit。
这篇文章将带你深入了解这两个库,并展示它们如何让 Flutter 的网络请求变得简单而强大。
第一部分:Dio - Flutter 的 HTTP 客户端之王
什么是 Dio?
Dio 是一个强大的 Dart HTTP 客户端,它基于 Dart 的 http
包,但提供了更多高级功能。如果你熟悉 iOS 的 Alamofire,那么 Dio 就是 Flutter 世界中的 Alamofire。
为什么选择 Dio?
- 拦截器支持:可以在请求发送前和响应接收后进行拦截处理
- 请求/响应转换:自动处理 JSON 序列化和反序列化
- 文件上传/下载:内置文件操作支持
- 请求取消:支持取消正在进行的请求
- 超时处理:灵活的超时配置
- 错误处理:完善的错误处理机制
基础使用示例
import 'package:dio/dio.dart';
void main() async {
// 创建 Dio 实例
final dio = Dio();
// 基础 GET 请求
try {
final response = await dio.get('https://api.example.com/users');
print('Response: ${response.data}');
} catch (e) {
print('Error: $e');
}
// POST 请求
try {
final response = await dio.post(
'https://api.example.com/users',
data: {
'name': 'John Doe',
'email': 'john@example.com'
},
);
print('Created user: ${response.data}');
} catch (e) {
print('Error: $e');
}
}
配置 Dio 实例
final dio = Dio(BaseOptions(
baseUrl: 'https://api.example.com',
connectTimeout: Duration(seconds: 5),
receiveTimeout: Duration(seconds: 3),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
));
拦截器 - Dio 的强大功能
拦截器是 Dio 最强大的功能之一,类似于 iOS 中的 URLSession 代理:
// 请求拦截器
dio.interceptors.add(InterceptorsWrapper(
onRequest: (options, handler) {
// 在请求发送前添加 token
options.headers['Authorization'] = 'Bearer $token';
print('Request: ${options.method} ${options.path}');
handler.next(options);
},
onResponse: (response, handler) {
// 处理响应
print('Response: ${response.statusCode}');
handler.next(response);
},
onError: (error, handler) {
// 处理错误
print('Error: ${error.message}');
handler.next(error);
},
));
第二部分:Retrofit - 让 API 接口更优雅
什么是 Retrofit?
Retrofit 是一个代码生成库,它让你可以用注解的方式定义 API 接口,然后自动生成实现代码。如果你熟悉 iOS 的 Moya,那么 Retrofit 就是 Flutter 中的 Moya。
为什么需要 Retrofit?
- 类型安全:编译时检查 API 调用的正确性
- 代码简洁:减少样板代码
- 易于维护:接口定义清晰,便于理解和修改
- 自动生成:无需手动编写 HTTP 请求代码
设置 Retrofit
首先在 pubspec.yaml
中添加依赖:
dependencies:
dio: ^5.0.0
retrofit: ^4.0.0
dev_dependencies:
retrofit_generator: ^7.0.0
build_runner: ^2.4.0
创建 API 接口
import 'package:dio/dio.dart';
import 'package:retrofit/retrofit.dart';
part 'user_api.g.dart';
()
abstract class UserApi {
factory UserApi(Dio dio, {String? baseUrl}) = _UserApi;
('/users')
Future<List<User>> getUsers();
('/users/{id}')
Future<User> getUser(('id') int id);
('/users')
Future<User> createUser(() User user);
('/users/{id}')
Future<User> updateUser(
('id') int id,
() User user,
);
('/users/{id}')
Future<void> deleteUser(('id') int id);
}
注解详解
HTTP 方法注解
('/users') // GET 请求
('/users') // POST 请求
('/users/{id}') // PUT 请求
('/users/{id}') // DELETE 请求
参数注解
('id') int id // URL 路径参数
('page') int page // 查询参数
() User user // 请求体
('name') String name // 表单字段
('Authorization') String token // 请求头
生成代码
运行以下命令生成实现代码:
flutter packages pub run build_runner build
这会生成 user_api.g.dart
文件,包含所有接口的具体实现。
第三部分:实际项目中的应用
完整的 API 服务示例
// api_service.dart
import 'package:dio/dio.dart';
import 'package:retrofit/retrofit.dart';
part 'api_service.g.dart';
()
abstract class ApiService {
factory ApiService(Dio dio, {String? baseUrl}) = _ApiService;
// 用户相关
('/users/profile')
Future<User> getProfile();
('/users/profile')
Future<User> updateProfile(() User user);
// 动态相关
('/moments')
Future<List<Moment>> getMoments({
('page') int page = 1,
('limit') int limit = 20,
});
('/moments')
Future<Moment> createMoment(() CreateMomentRequest request);
// 文件上传
('/upload')
()
Future<UploadResponse> uploadFile(() File file);
}
配置 Dio 实例
// dio_config.dart
class DioConfig {
static Dio createDio() {
final dio = Dio(BaseOptions(
baseUrl: 'https://api.example.com',
connectTimeout: Duration(seconds: 10),
receiveTimeout: Duration(seconds: 10),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
));
// 添加拦截器
dio.interceptors.addAll([
_AuthInterceptor(),
_LoggingInterceptor(),
_ErrorInterceptor(),
]);
return dio;
}
}
class _AuthInterceptor extends Interceptor {
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
// 添加认证 token
final token = getStoredToken();
if (token != null) {
options.headers['Authorization'] = 'Bearer $token';
}
handler.next(options);
}
}
在 Repository 中使用
// user_repository.dart
class UserRepository {
final ApiService _apiService;
UserRepository() : _apiService = ApiService(DioConfig.createDio());
Future<User> getProfile() async {
try {
return await _apiService.getProfile();
} catch (e) {
throw UserException('获取用户信息失败: $e');
}
}
Future<User> updateProfile(User user) async {
try {
return await _apiService.updateProfile(user);
} catch (e) {
throw UserException('更新用户信息失败: $e');
}
}
}
第四部分:与 iOS 开发的对比
概念映射
iOS | Flutter | 说明 |
---|---|---|
URLSession | Dio | HTTP 客户端 |
Alamofire | Dio | 高级 HTTP 客户端 |
Moya | Retrofit | API 接口抽象 |
Codable | json_annotation | JSON 序列化 |
优势对比
Flutter 的优势:
- 类型安全:编译时检查,减少运行时错误
- 代码生成:自动生成样板代码
- 跨平台:一套代码,多平台运行
- 热重载:开发效率更高
iOS 的优势:
- 生态系统成熟:更多第三方库
- 性能优化:原生性能
- 平台特性:更好的平台集成
第五部分:最佳实践
1. 错误处理
class ApiException implements Exception {
final String message;
final int? statusCode;
ApiException(this.message, {this.statusCode});
String toString() => 'ApiException: $message (Status: $statusCode)';
}
// 在拦截器中处理错误
class _ErrorInterceptor extends Interceptor {
void onError(DioException err, ErrorInterceptorHandler handler) {
switch (err.type) {
case DioExceptionType.connectionTimeout:
throw ApiException('连接超时');
case DioExceptionType.receiveTimeout:
throw ApiException('接收超时');
case DioExceptionType.badResponse:
final statusCode = err.response?.statusCode;
final message = err.response?.data['message'] ?? '请求失败';
throw ApiException(message, statusCode: statusCode);
default:
throw ApiException('网络错误: ${err.message}');
}
}
}
2. 响应包装
// 统一响应格式
class ApiResponse<T> {
final bool success;
final T? data;
final String? message;
final int? code;
ApiResponse({
required this.success,
this.data,
this.message,
this.code,
});
factory ApiResponse.fromJson(Map<String, dynamic> json, T Function(dynamic) fromJson) {
return ApiResponse<T>(
success: json['success'] ?? false,
data: json['data'] != null ? fromJson(json['data']) : null,
message: json['message'],
code: json['code'],
);
}
}
3. 缓存策略
class CacheInterceptor extends Interceptor {
final Map<String, dynamic> _cache = {};
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
if (options.method == 'GET' && _cache.containsKey(options.path)) {
// 返回缓存数据
final cachedResponse = _cache[options.path];
handler.resolve(Response(
data: cachedResponse,
requestOptions: options,
));
return;
}
handler.next(options);
}
void onResponse(Response response, ResponseInterceptorHandler handler) {
if (response.requestOptions.method == 'GET') {
_cache[response.requestOptions.path] = response.data;
}
handler.next(response);
}
}
总结
Dio + Retrofit 的组合为 Flutter 开发者提供了强大而优雅的网络请求解决方案。对于从 iOS 转向 Flutter 的开发者来说,这个组合提供了:
- 熟悉的开发体验:类似 Alamofire + Moya 的使用方式
- 类型安全:编译时检查,减少错误
- 代码简洁:自动生成样板代码
- 易于维护:清晰的接口定义
通过合理使用这两个库,你可以构建出健壮、可维护的网络层,为你的 Flutter 应用提供强大的后端支持。
记住,好的网络层设计是应用成功的基础。投入时间学习这些工具,将会在长期开发中带来巨大的回报。