Im using connectivity package to track users connection changes. The idea is to pop up a warning page for connection loss when the ConnectivityResult is none (aka wifi and mobile is disconnected). But instead i get these results : If the wifi is connected and you disconnect it, 50% of the time the warning pops up. If you are on mobile and turn it off, the connectivity returns that user is still on ConnectivityResult.mobile not ConnectivityResult.none.
Tried to make a doublecheck with pinging google, but even that doesnt work as smooth as i expected it to be.
My code : I have created seperated file with functions :
void trackNetworkStatus(BuildContext ctx) {
//check in case state is just opened
pingGoogle(ctx);
//add network listener
Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
print("Network changed to $result");
//if user lost connection
if (result == ConnectivityResult.none) {
openNoInternetScreen(ctx);
}else{
//if user has connection, doublecheck
//mobile network is tricky on android
pingGoogle(ctx);
}
});
}
Future<void> pingGoogle(BuildContext ctx) async {
try {
//ping internet page
final result = await InternetAddress.lookup('google.com');
//if ping is successful
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
}else{
print('not connected');
openNoInternetScreen(ctx);
}
} on SocketException catch (_) {
print('not connected');
openNoInternetScreen(ctx);
}
}
void openNoInternetScreen(BuildContext ctx) {
Navigator.push(
ctx,
MaterialPageRoute(builder: (context) => noInternetPage()),
);
}
because i am calling them on every apps init like this :
@override
void initState() {
super.initState();
//listen to netwoek changes
trackNetworkStatus(context);
}
which leads to problem that sometimes warning page pops up twice because, as i believe, the previous listener has not been stopped, but i can figure out how to fix it. The question is why connectivity package returns false callback on mobile. Ive tested on virtual Android API 23 and Samsung S9+, both share same results.