|
|
@@ -0,0 +1,42 @@
|
|
|
+import 'package:connectivity_plus/connectivity_plus.dart';
|
|
|
+import 'package:dio/dio.dart';
|
|
|
+import '../exceptions/no_network_exception.dart';
|
|
|
+
|
|
|
+/// 网络状态拦截器
|
|
|
+///
|
|
|
+/// 在发送请求前检查网络连接状态,如果没有网络则抛出 [NoNetworkException]
|
|
|
+class NetworkInterceptor extends Interceptor {
|
|
|
+ @override
|
|
|
+ Future<void> onRequest(
|
|
|
+ RequestOptions options,
|
|
|
+ RequestInterceptorHandler handler,
|
|
|
+ ) async {
|
|
|
+ // 检查网络连接
|
|
|
+ final connectivityResult = await Connectivity().checkConnectivity();
|
|
|
+
|
|
|
+ // 检查是否有可用网络 (WiFi 或 Mobile)
|
|
|
+ // ConnectivityResult 包含 none 表示无网络
|
|
|
+ // 实际上只要列表中包含 mobile 或 wifi 就认为有网
|
|
|
+ final bool hasNetwork = connectivityResult.any(
|
|
|
+ (result) => result == ConnectivityResult.mobile || result == ConnectivityResult.wifi
|
|
|
+ );
|
|
|
+
|
|
|
+ // 如果没有网络(或者是其他未处理的类型且不是 wifi/mobile,严格来说应该根据业务需求。
|
|
|
+ // 这里简单起见,如果没有 wifi 且没有 mobile,就认为无网,或者如果只包含 none)
|
|
|
+ // 更准确的逻辑:如果 connectivityResult 包含 none 且不包含 mobile/wifi (实际上 none 不会和 mobile/wifi 共存)
|
|
|
+
|
|
|
+ // 简单判断:只要不包含 mobile 和 wifi
|
|
|
+ if (!hasNetwork) {
|
|
|
+ return handler.reject(
|
|
|
+ DioException(
|
|
|
+ requestOptions: options,
|
|
|
+ error: NoNetworkException(),
|
|
|
+ type: DioExceptionType.connectionError,
|
|
|
+ ),
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ super.onRequest(options, handler);
|
|
|
+ }
|
|
|
+}
|
|
|
+
|