Member-only story
Flutter — How to Check Internet Connection
Check whether the device have internet connectivity.
2 min readSep 13, 2021
Plugin: connectivity
One time check
Future<bool> hasNetwork() async {
try {
final result = await InternetAddress.lookup('example.com');
return result.isNotEmpty && result[0].rawAddress.isNotEmpty;
} on SocketException catch (_) {
return false;
}
}bool isOnline = await hasNetwork();
Setting up a listener
void main() => runApp(MaterialApp(home: HomePage()));
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Map _source = {ConnectivityResult.none: false};
final MyConnectivity _connectivity = MyConnectivity.instance;
@override
void initState() {
super.initState();
_connectivity.initialise();
_connectivity.myStream.listen((source) {
setState(() => _source = source);
});
}
@override
Widget build(BuildContext context) {
String string;
switch (_source.keys.toList()[0]) {
case ConnectivityResult.mobile:
string = 'Mobile: Online';
break;
case ConnectivityResult.wifi:
string = 'WiFi: Online';
break;
case ConnectivityResult.none…