net_dio_request
一个基于 Dio 封装的 Flutter 网络请求插件,内置常用的 GET、POST 请求方法,并通过 qs_toast 提供可选的 loading 提示。
环境要求
- Dart SDK:
^2.17.0 - Flutter:
>=3.0.0
安装
在项目的 pubspec.yaml 中添加依赖:
dependencies:
net_dio_request: ^1.0.0
如果还没有发布到 pub.dev,也可以使用 Git 依赖:
dependencies:
net_dio_request:
git:
url: https://github.com/fallpine/net_dio_request.git
然后执行:
flutter pub get
导入
import 'package:net_dio_request/net_request.dart';
import 'package:net_dio_request/net_request_exception.dart';
如果只需要获取平台版本,可以导入:
import 'package:net_dio_request/net_dio_request.dart';
基础配置
插件默认连接超时和接收超时都是 30 秒。你也可以在应用启动时手动配置:
void main() {
NetRequest.shared.config(
connectTimeout: const Duration(seconds: 15),
receiveTimeout: const Duration(seconds: 15),
);
runApp(const MyApp());
}
发起 GET 请求
获取 JSON
Future<void> loadUser() async {
try {
final result = await NetRequest.shared.getJson(
'https://example.com/api/user',
parameters: {
'id': 1,
},
headers: {
'Authorization': 'Bearer your_token',
},
);
print(result);
} on NetRequestException catch (e) {
print('请求失败: ${e.code}, ${e.message}');
}
}
获取字符串
Future<void> loadText() async {
try {
final result = await NetRequest.shared.getString(
'https://example.com/api/text',
isShowLoading: false,
);
print(result);
} on NetRequestException catch (e) {
print('请求失败: ${e.code}, ${e.message}');
}
}
发起 POST 请求
Future<void> createUser() async {
try {
final result = await NetRequest.shared.postJson(
'https://example.com/api/user',
parameters: {
'name': 'Tom',
'age': 18,
},
headers: {
'Content-Type': 'application/json',
},
);
print(result);
} on NetRequestException catch (e) {
print('请求失败: ${e.code}, ${e.message}');
}
}
Loading 提示
getJson、getString 和 postJson 默认会显示 loading:
await NetRequest.shared.getJson('https://example.com/api/list');
如果某个请求不需要 loading,可以设置 isShowLoading: false:
await NetRequest.shared.getJson(
'https://example.com/api/list',
isShowLoading: false,
);
异常处理
所有网络方法都可能抛出 NetRequestException,建议统一使用 try-catch 捕获。
try {
final data = await NetRequest.shared.getJson('https://example.com/api/list');
print(data);
} on NetRequestException catch (e) {
print(e.toString());
}
常见错误码:
| 错误码 | 含义 |
|---|---|
-10000 |
数据解析失败 |
-10001 |
Dio 请求异常 |
| HTTP 状态码 | 服务端返回的非 200 状态码 |
API 说明
| 方法 | 说明 |
|---|---|
NetRequest.shared.config |
配置连接超时和接收超时 |
NetRequest.shared.getJson |
发起 GET 请求,并解析为 Map<String, dynamic>? |
NetRequest.shared.getString |
发起 GET 请求,并解析为 String? |
NetRequest.shared.postJson |
发起 POST 请求,并解析为 Map? |
NetDioRequest().getPlatformVersion |
获取当前平台版本 |
平台支持
当前插件包含 Android 和 iOS 平台实现。
示例项目
可以查看 example/ 目录中的 Flutter 示例工程:
cd example
flutter run