network_check_helper.dart 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import 'dart:async';
  2. import 'package:connectivity_plus/connectivity_plus.dart';
  3. import 'package:flutter/services.dart';
  4. import 'log_util.dart';
  5. typedef NetworkCheckHelperDelegate = void Function(ConnectivityResult result);
  6. class NetworkCheckHelper {
  7. factory NetworkCheckHelper() => _instance;
  8. static final NetworkCheckHelper _instance =
  9. NetworkCheckHelper._internal();
  10. NetworkCheckHelper._internal();
  11. final Connectivity _connectivity = Connectivity();
  12. NetworkCheckHelperDelegate? delegate;
  13. StreamSubscription<ConnectivityResult>? _connectivitySubscription;
  14. void setDelegate(NetworkCheckHelperDelegate d) {
  15. delegate = d;
  16. _connectivitySubscription = _connectivity.onConnectivityChanged.listen((event) {
  17. if (delegate != null) {
  18. delegate!(event);
  19. }
  20. });
  21. }
  22. void clearDelegate() {
  23. delegate = null;
  24. _connectivitySubscription?.cancel();
  25. }
  26. Future<bool> checkConnectivity() async {
  27. try {
  28. final result = await _connectivity.checkConnectivity();
  29. return !(result == ConnectivityResult.none);
  30. } on PlatformException catch (e) {
  31. OLogger.e('Couldn\'t check connectivity status' , e);
  32. return false;
  33. }
  34. }
  35. }