Flutter Http请求库-dio
封面图
•
2025-10-13
•
Flutter
0
0
0
0
`Dio` 是一个功能强大的 **Flutter/Android/iOS** 网络请求库,是 Flutter 中最常用的 HTTP 请求库之一。它支持多种功能,如: - 支持 `GET`, `POST`, `PUT`, `DELETE` 等多种 HTTP 方法 - 支持拦截器(Interceptor) - 支持文件上传和下载 - 支持超时、重试、缓存等 - 支持 `FormData` 上传 - 支持 `Dart` 和 `JavaScript` 环境 --- ## 📦 安装 Dio 在 `pubspec.yaml` 文件中添加依赖: ```yaml dependencies: dio: ^4.0.0 # 请查看最新版本 ``` 然后运行: ```bash flutter pub get ``` --- ## 🚀 基本使用示例 ### 1. GET 请求 ```dart import 'package:dio/dio.dart'; void fetchData() async { try { final response = await Dio().get('https://jsonplaceholder.typicode.com/posts'); print(response.data); } catch (e) { print('Error: $e'); } } ``` ### 2. POST 请求 ```dart final data = {'title': 'foo', 'body': 'bar', 'userId': 1}; final response = await Dio().post( 'https://jsonplaceholder.typicode.com/posts', data: data, ); print(response.data); ``` ### 3. 使用拦截器 ```dart final dio = Dio(); dio.interceptors.add(InterceptorsWrapper( onRequest: (options, handler) { print('Request: ${options.uri}'); return handler.next(options); }, onResponse: (response, handler) { print('Response: ${response.statusCode}'); return handler.next(response); }, onError: (e, handler) { print('Error: ${e.message}'); return handler.next(e); }, )); ``` --- ## 🔧 高级功能 ### 1. 设置基础 URL ```dart final dio = Dio(BaseOptions( baseUrl: 'https://jsonplaceholder.typicode.com', )); await dio.get('/posts'); ``` ### 2. 添加 headers ```dart await dio.get('/posts', options: Options(headers: { 'Authorization': 'Bearer token123', })); ``` ### 3. 超时设置 ```dart final dio = Dio(BaseOptions( connectTimeout: 5000, // 连接超时 receiveTimeout: 3000, // 接收超时 )); ``` ### 4. 文件上传 ```dart final file = File('path/to/file.jpg'); final formData = FormData.fromMap({ 'file': await MultipartFile.fromFile(file.path), }); await dio.post('/upload', data: formData); ``` ### 5. 下载文件 ```dart await dio.download( 'https://example.com/file.txt', './downloaded_file.txt', onReceiveProgress: (received, total) { print('Downloaded: $received / $total'); }, ); ``` --- ## ✅ 总结 | 功能 | 是否支持 | |------|----------| | GET/POST/PUT/DELETE | ✅ | | 拦截器 | ✅ | | 文件上传 | ✅ | | 文件下载 | ✅ | | 超时设置 | ✅ | | 缓存 | ✅(配合 `dio_cache_interceptor`) | | 自定义 Headers | ✅ | --- 如果你需要更高级的功能(如缓存、认证、Mock 等),可以结合 `dio_cache_interceptor` 或 `http_cache_flutter` 等插件。 --- 如果你有具体需求(比如登录、图片上传、错误处理等),我可以提供更详细的代码示例 😊
上一篇:
Flutter JSON转Dart Model类
标题录入,一次不能超过6条
返回顶部
留言
留言
评论