我在我的flutter web应用程序中获取互联网状态,通过在我的服务中实现以下代码:
```import 'dart:async';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:rxdart/rxdart.dart';
enum ConnectionStatus {
online,
offline,
}
class CheckInternetConnection {
final Connectivity _connectivity = Connectivity();
/// We assume the initial status is Online
final _controller = BehaviorSubject.seeded(ConnectionStatus.online);
StreamSubscription? _connectionSubscription;
CheckInternetConnection() {
_checkInternetConnection();
}
Stream<ConnectionStatus> internetStatus() {
_connectionSubscription ??= _connectivity.onConnectivityChanged
.listen((_) => _checkInternetConnection());
return _controller.stream;
}
Future<void> _checkInternetConnection() async {
try {
// Sometimes the callback is called when we reconnect to wifi,
// but the internet is not really functional
// This delay try to wait until we are really connected to internet
final result = await InternetAddress.lookup('www.google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
_controller.sink.add(ConnectionStatus.online);
} else {
_controller.sink.add(ConnectionStatus.offline);
}
} on SocketException catch (_) {
_controller.sink.add(ConnectionStatus.offline);
}
}
Future<void> close() async {
await _connectionSubscription?.cancel();
await _controller.close();
}
}
但我得到以下错误:
'''Error: Unsupported operation: InternetAddress.lookup
at Object.throw_ [as throw] (http://localhost:50773/dart_sdk.js:5080:11)
at InternetAddress.lookup (http://localhost:50773/dart_sdk.js:59860:17)
at internet_conection_service.CheckInternetConnection.new._checkInternetConnection (http://localhost:50773/packages/flutter_web/src/core/services/internet_conection_service.dart.lib.js:86:50)
at _checkInternetConnection.next (<anonymous>)
at runBody (http://localhost:50773/dart_sdk.js:40660:34)
at Object._async [as async] (http://localhost:50773/dart_sdk.js:40691:7)
at [_checkInternetConnection] (http://localhost:50773/packages/flutter_web/src/core/services/internet_conection_service.dart.lib.js:84:20)'''```
我已经尝试将dart:io更改为universal:io,但出现以下错误:
'''Error: UnimplementedError
at Object.throw_ [as throw] (http://localhost:50773/dart_sdk.js:5080:11)
at InternetAddress.lookup (http://localhost:50773/packages/universal_io/src/io/sync_socket.dart.lib.js:3038:24)
at internet_conection_service.CheckInternetConnection.new._checkInternetConnection (http://localhost:50773/packages/flutter_web/src/core/services/internet_conection_service.dart.lib.js:87:64)
at _checkInternetConnection.next (<anonymous>)
at runBody (http://localhost:50773/dart_sdk.js:40660:34)'''
你能帮我一些选项,以便能够解决它在扑网,因为在移动的我没有问题.谢谢.
2条答案
按热度按时间z8dt9xmd1#
我也面临这个问题,因为我正在使用以下方法来检查互联网连接:
然后我把这个方法改为:
它解决了我的问题。
ilmyapht2#
虽然公认的答案是好的,但我认为这是一个更好的方法:当应用程序在浏览器上运行时,仅使用接受的答案。默认情况下,使用常规查找,这样更快。
顺便说一句,
knownUrl
可能是你的项目网站,如果你有一个。你必须确定是否为你启用了CORS。如果你不确定,只是尝试google.com
,example.com
和URL类似。