network_connectivity.dart 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import 'dart:async';
  2. import 'package:connectivity_plus/connectivity_plus.dart';
  3. import 'package:flutter/foundation.dart';
  4. import 'package:vnote_device_plugin/events/event_type.dart';
  5. import 'package:fis_common/logger/logger.dart';
  6. import 'package:fis_common/env/env.dart';
  7. /// 网络连接检测器 - 全局实例
  8. final netChecker = _init();
  9. NetworkConnectivityChecker _init() {
  10. final instance = NetworkConnectivityChecker._();
  11. bool isConnecting = true;
  12. instance.onlineChangedEvent.addListener((sender, e) {
  13. if (e) {
  14. if (!isConnecting) {
  15. // TODO: 暂时不提示
  16. // PromptBox.toast("网络已连接");
  17. }
  18. } else {
  19. // TODO: 暂时不提示
  20. // PromptBox.error("网络已断开");
  21. }
  22. isConnecting = e;
  23. });
  24. return instance;
  25. }
  26. /// 网络连接检查器
  27. class NetworkConnectivityChecker {
  28. NetworkConnectivityChecker._();
  29. final Connectivity _api = Connectivity();
  30. StreamSubscription<ConnectivityResult>? _subscription;
  31. ConnectivityResult _status = ConnectivityResult.none;
  32. /// 在线状态变更事件
  33. final FEventHandler<bool> onlineChangedEvent = FEventHandler<bool>();
  34. /// 连接状态
  35. ConnectivityResult get status => _status;
  36. FPlatformEnum get platform => FPlatform.current;
  37. /// 是否在线
  38. bool get isOnline {
  39. if (kIsWeb) {
  40. return true;
  41. }
  42. return status != ConnectivityResult.none;
  43. }
  44. void run() {
  45. if (_subscription != null) {
  46. return;
  47. }
  48. _subscription = _api.onConnectivityChanged.listen((event) {
  49. logger.i(
  50. "NetworkConnectivityChecker - Current net connection type: ${event.name}.");
  51. _update(event);
  52. logger.i("NetworkConnectivityChecker - IsOnline: $isOnline.");
  53. });
  54. }
  55. void stop() {
  56. _subscription?.cancel();
  57. _subscription = null;
  58. }
  59. /// 手动检查
  60. Future<bool> check() async {
  61. logger.i("NetworkConnectivityChecker - Check start.");
  62. final result = await _api.checkConnectivity();
  63. logger.i("NetworkConnectivityChecker - Check result:${result.name}.");
  64. _update(result);
  65. logger.i("NetworkConnectivityChecker - IsOnline: $isOnline.");
  66. return isOnline;
  67. }
  68. void _update(ConnectivityResult result) {
  69. _status = result;
  70. onlineChangedEvent.emit(this, isOnline);
  71. }
  72. }