当前位置: 首页 > news >正文

Flutter网络请求实战:Retrofit+Dio完美解决方案

Flutter网络请求:Retrofit使用指南

Retrofit是Android平台上广受欢迎的HTTP客户端库,在Flutter中可以通过retrofit包实现类似的网络请求功能。下面是完整的使用指南:

1. 添加依赖

首先在pubspec.yaml中添加所需依赖:

dependencies:retrofit: ^4.0.1dio: ^5.3.2json_annotation: ^4.8.1dev_dependencies:retrofit_generator: ^4.0.1build_runner: ^2.4.4

2. 创建API接口

定义一个抽象类来描述你的API接口:

import 'package:retrofit/retrofit.dart';
import 'package:dio/dio.dart';
import 'package:json_annotation/json_annotation.dart';part 'api_service.g.dart';(baseUrl: "https://jsonplaceholder.typicode.com/")
abstract class ApiService {factory ApiService(Dio dio, {String baseUrl}) = _ApiService;("/posts")Future<List<Post>> getPosts();("/posts/{id}")Future<Post> getPost(("id") int id);("/posts")Future<Post> createPost(() Post post);
}()
class Post {final int id;final String title;final String body;final int userId;Post({required this.id,required this.title,required this.body,required this.userId,});factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json);Map<String, dynamic> toJson() => _$PostToJson(this);
}

3. 生成代码

运行以下命令生成实现代码:

flutter pub run build_runner build

这会生成api_service.g.dart文件。

4. 使用API服务

void main() async {final dio = Dio();final apiService = ApiService(dio);try {// 获取所有帖子final posts = await apiService.getPosts();print(posts);// 获取单个帖子final post = await apiService.getPost(1);print(post);// 创建新帖子final newPost = await apiService.createPost(Post(id: 101, title: 'New Post', body: 'Content', userId: 1),);print(newPost);} catch (e) {print(e);}
}

5. 高级功能

添加请求头

("/posts")
({'Content-Type': 'application/json'})
Future<List<Post>> getPosts();

查询参数

("/posts")
Future<List<Post>> getPostsByUser(("userId") int userId);

表单数据

("/login")
()
Future<User> login(("username") String username,("password") String password,
);

拦截器

final dio = Dio()..interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {// 添加认证tokenoptions.headers['Authorization'] = 'Bearer token';return handler.next(options);},onError: (DioError e, handler) {// 错误处理return handler.next(e);},),);

6. 完整配置示例

import 'package:dio/dio.dart';
import 'package:retrofit/retrofit.dart';part 'api_service.g.dart';(baseUrl: "https://api.example.com/v1/")
abstract class ApiService {factory ApiService(Dio dio, {String baseUrl}) {dio.options = BaseOptions(receiveTimeout: const Duration(seconds: 30),connectTimeout: const Duration(seconds: 30),);return _ApiService(dio, baseUrl: baseUrl);}("users")Future<List<User>> getUsers();("users/{id}")Future<User> getUser(("id") String id);("users")Future<User> createUser(() User user);("users/{id}")Future<User> updateUser(("id") String id, () User user);("users/{id}")Future<void> deleteUser(("id") String id);
}

7. 错误处理

try {final response = await apiService.getUser('123');
} on DioError catch (e) {if (e.response != null) {print(e.response?.statusCode);print(e.response?.data);} else {print(e.message);}
}

8. 测试API服务

test('getPosts returns List<Post>', () async {final dio = DioAdapterMock();final apiService = ApiService(dio);when(dio.get('/posts')).thenAnswer((_) async => Response(data: [{'id': 1, 'title': 'Test', 'body': 'Content', 'userId': 1}],statusCode: 200,requestOptions: RequestOptions(path: '/posts'),));final posts = await apiService.getPosts();expect(posts, isA<List<Post>>());expect(posts.first.title, 'Test');
});

Retrofit为Flutter提供了类型安全的HTTP客户端实现,通过代码生成简化了网络请求的编写,同时保持了Dio的强大功能。

http://www.lryc.cn/news/619586.html

相关文章:

  • 51单片机-51单片机最小系统
  • 区块链DApp:颠覆未来的去中心化应用
  • 性能优化之通俗易懂学习requestAnimationFrame和使用场景举例
  • PyTorch生成式人工智能——基于Transformer实现文本转语音
  • 浅谈TLS 混合密钥交换:后量子迁移过渡方案
  • [TG开发]简单的回声机器人
  • 科技赋能虚拟形象:3D人脸扫描设备的应用与未来
  • vscode+phpstudy+xdebug如何调试php
  • 【R语言】R语言的工作空间映像(workspace image,通常是.RData)详解
  • YOLO v1 输出结构、预测逻辑与局限性详解
  • 教育元宇宙:一场重构教育生态的数字革命
  • 在实验室连接地下车库工控机及其数据采集设备
  • 面向局部遮挡场景的目标检测系统设计与实现
  • 开源WAF新标杆:雷池SafeLine用语义分析重构网站安全边界
  • Go语言实战案例:使用Gin处理路由参数和查询参数
  • .net\c#web、小程序、安卓开发之基于asp.net家用汽车销售管理系统的设计与实现
  • Redis学习——Redis的十大类型String、List、Hash、Set、Zset
  • SQL详细语法教程(一)--数据定义语言(DDL)
  • PCIe Base Specification解析(十)
  • 基于机器学习的自动驾驶汽车新型失效运行方法
  • BGP综合实验_Te. BGP笔记
  • Python实战教程:PDF文档自动化编辑与图表绘制全攻略
  • Blender模拟结构光3D Scanner(一)外参数匹配
  • 解决:nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module
  • PyTorch神经网络工具箱(神经网络核心组件)
  • 第十二节:粒子系统:海量点渲染
  • 5.0.9.1 C# wpf通过WindowsFormsHost嵌入windows media player(AxInterop.WMPLib)
  • Go 1.25正式发布
  • ant-design a-from-model的校验
  • 自然语言处理的实际应用