initial commit: push everything
This commit is contained in:
55
lib/controllers/connectivity_mixin.dart
Normal file
55
lib/controllers/connectivity_mixin.dart
Normal file
@@ -0,0 +1,55 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
mixin ConnectivityControllerMixin on GetxController {
|
||||
final RxBool isOnline = true.obs;
|
||||
Timer? _tick;
|
||||
|
||||
@protected
|
||||
Future<bool> checkInternet() async {
|
||||
try {
|
||||
final result = await InternetAddress.lookup('example.com');
|
||||
return result.isNotEmpty && result.first.rawAddress.isNotEmpty;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@protected
|
||||
void onConnectivityOnline() {}
|
||||
|
||||
@protected
|
||||
void onConnectivityOffline() {}
|
||||
|
||||
void _startWatcher() {
|
||||
_tick?.cancel();
|
||||
_tick = Timer.periodic(const Duration(seconds: 5), (_) async {
|
||||
final ok = await checkInternet();
|
||||
final prev = isOnline.value;
|
||||
if (ok != prev) {
|
||||
isOnline.value = ok;
|
||||
if (ok) {
|
||||
onConnectivityOnline();
|
||||
} else {
|
||||
onConnectivityOffline();
|
||||
}
|
||||
} else {
|
||||
isOnline.value = ok;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
_startWatcher();
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_tick?.cancel();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user