network.dart 953 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import 'dart:async';
  2. import 'package:connectivity/connectivity.dart';
  3. class Network {
  4. static bool _isAvailable = false;
  5. static bool isAvailable() {
  6. return _isAvailable;
  7. }
  8. static Future<bool> isNetworkAvailable() async {
  9. var connectivityResult = await Connectivity().checkConnectivity();
  10. bool result = false;
  11. if (connectivityResult != ConnectivityResult.none) {
  12. result = true;
  13. }
  14. Network._isAvailable = result;
  15. print("isAvailable: $_isAvailable");
  16. return result;
  17. }
  18. static void init() async {
  19. await isNetworkAvailable();
  20. Connectivity().onConnectivityChanged.listen((ConnectivityResult result) async {
  21. print("Network changed!");
  22. return await isNetworkAvailable();
  23. });
  24. }
  25. static void registerSubscription(Function callback) {
  26. Connectivity().onConnectivityChanged.listen((ConnectivityResult result) async {
  27. print("Network changed!");
  28. callback();
  29. });
  30. }
  31. }