-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbase_controller.dart
65 lines (60 loc) · 1.87 KB
/
base_controller.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:get/get.dart';
import 'package:srlm_app/global/connectivity_status.dart';
import 'package:srlm_app/utils/custom_print.dart';
class BaseController extends GetxController {
RxBool hasInternet = RxBool(false);
RxBool isLoading = RxBool(false);
@override
void onInit() {
handleInternetConnectivity();
super.onInit();
}
Future<void> handleInternetConnectivity() async {
try {
await checkInternetStream().forEach((data) {
if (hasInternet.value != data) {
hasInternet.value = data;
if (data) {
printWarning('connected');
} else {
printWarning('not connected');
}
}
});
} catch (e) {
// No internet
hasInternet.value = false;
}
}
Stream<bool> checkInternetStream() async* {
List<InternetAddress> result;
while (true) {
try {
if (ConnectivityStatus.connectivityResult == null ||
ConnectivityStatus.connectivityResult == ConnectivityResult.none) {
final connectivityResult = await Connectivity().checkConnectivity();
ConnectivityStatus.setConnectivity(connectivityResult);
}
if (ConnectivityStatus.connectivityResult == ConnectivityResult.none) {
yield false;
continue;
}
result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
yield true;
await Future.delayed(const Duration(milliseconds: 500));
} else {
yield false;
}
} on SocketException catch (_) {
yield false;
await Future.delayed(const Duration(milliseconds: 500));
} catch (e) {
yield false;
await Future.delayed(const Duration(milliseconds: 500));
}
}
}
}