Flutter如何实现Dio+Retrofit网络请求
在Flutter项目中,我想使用Dio结合Retrofit来实现网络请求,但不太清楚具体的实现步骤。请问:
- 如何正确配置Dio和Retrofit的依赖?
- Retrofit的注解该如何使用来定义API接口?
- 如何处理网络请求的异常和错误?
- 是否有完整的示例代码可以参考?
- 在实际项目中需要注意哪些性能优化点?
2 回复
在Flutter中,使用Dio和Retrofit实现网络请求:
- 添加依赖:
dio、retrofit、json_annotation、build_runner。 - 创建数据模型,使用
json_annotation注解。 - 定义API接口,用
@RestApi()和@GET()等注解。 - 运行
build_runner生成代码:flutter pub run build_runner build。 - 使用生成的客户端发起请求。
更多关于Flutter如何实现Dio+Retrofit网络请求的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中实现类似Retrofit的网络请求,通常使用Dio作为HTTP客户端,配合retrofit库(一个Dio的代码生成器)来实现。以下是具体步骤:
1. 添加依赖
在pubspec.yaml中添加:
dependencies:
dio: ^5.0.0
retrofit: ^5.0.0
logger: ^1.0.0
dev_dependencies:
build_runner: ^2.0.0
retrofit_generator: ^5.0.0
2. 创建API接口定义
使用注解定义API接口:
import 'package:retrofit/retrofit.dart';
import 'package:dio/dio.dart';
part 'api_service.g.dart';
@RestApi(baseUrl: "https://jsonplaceholder.typicode.com/")
abstract class ApiService {
factory ApiService(Dio dio, {String baseUrl}) = _ApiService;
[@GET](/user/GET)("/posts/{id}")
Future<Post> getPost([@Path](/user/Path)("id") int id);
[@POST](/user/POST)("/posts")
Future<Post> createPost(@Body() Post post);
}
3. 生成代码
运行命令生成实现代码:
flutter pub run build_runner build
4. 使用示例
// 创建Dio实例
final dio = Dio()
..interceptors.add(LogInterceptor(responseBody: true));
// 创建API服务实例
final apiService = ApiService(dio);
// 调用API
try {
final post = await apiService.getPost(1);
print(post.title);
} catch (e) {
print(e);
}
5. 数据模型
定义对应的数据模型类(可使用json_annotation生成序列化代码):
class Post {
final int id;
final String title;
Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) =>
Post(id: json['id'], title: json['title']);
}
主要特性
- 注解驱动:@GET、@POST、@Path、@Query等注解
- 自动序列化:配合json_annotation实现自动JSON转换
- 拦截器支持:通过Dio添加日志、认证等拦截器
- 错误处理:统一处理网络异常和业务错误
这种方式减少了模板代码,提供了类型安全的API调用,是Flutter中最接近Android Retrofit的实现方案。

