I was trying to check the internet connection on my flutter app with the help of connectivity plus package and a function which I saw in one of the answers of stackoverflaw. Below is the code:
connectivity_check.dart
import 'dart:async';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
enum ConnectivityStatus { Online, Offline }
class ConnectivityService {
// Create our public controller
StreamController<ConnectivityStatus> connectionStatusController =
StreamController<ConnectivityStatus>();
final _connectivity = Connectivity();
ConnectivityService() {
// Subscribe to the connectivity Chanaged Steam
_connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
_checkStatus(result);
});
void _checkStatus(ConnectivityResult result) async {
bool isOnline = false;
try {
final result = await InternetAddress.lookup('example.com');
isOnline = result.isNotEmpty && result[0].rawAddress.isNotEmpty;
print(isOnline);
} on SocketException catch (_) {
isOnline = false;
}
if (isOnline == true)
connectionStatusController.sink.add(ConnectivityStatus.Online);
else
connectionStatusController.sink.add(ConnectivityStatus.Offline);
}
void disposeStream() => connectionStatusController.close();
}
StreamProvider in main.dart
StreamProvider<ConnectivityStatus>(
initialData: ConnectivityStatus.Online,
create: (_) =>
ConnectivityService().connectionStatusController.stream)
The Widget where I am using this connectivity provider
class OfferPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: (Provider.of<ConnectivityStatus>(context) ==
ConnectivityStatus.Online)
? ListView(
children: [
OfferImage(image: 'offer_banner.jpg'),
OfferImage(image: 'offer1.jpg'),
OfferImage(image: 'offer2.jpg'),
],
)
: Text('ok'),
);
}
}
The problem which I am facing is that the isOnline is always returning true even if I switch off my Wifi/data. Whenever stream provider listens to change in network, it returns true/Online, it doesn't return false/Offline. Can someone help and debug the code?