Is there any way in flutter to check internet connectivity without using "provider"? I've tried it with it doesn't seems good to me. Thanks in advance
Asked
Active
Viewed 1,999 times
0
-
Are you referring checking internet or sharing the statue ? Also you can try riverpod – Md. Yeasin Sheikh Aug 17 '22 at 12:09
-
Does this answer your question? [Check whether there is an Internet connection available on Flutter app](https://stackoverflow.com/questions/49648022/check-whether-there-is-an-internet-connection-available-on-flutter-app) – user18309290 Aug 17 '22 at 15:00
3 Answers
2
Use this package: https://pub.dev/packages/connectivity_plus
import 'package:connectivity_plus/connectivity_plus.dart';
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
// I am connected to a mobile network.
} else if (connectivityResult == ConnectivityResult.wifi) {
// I am connected to a wifi network.
}

MCB
- 503
- 1
- 8
- 21
2
import 'dart:io';
Future<bool> checkNetwork() async {
bool isConnected = false;
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
isConnected = true;
}
} on SocketException catch (_) {
isConnected = false;
}
return isConnected;
}
Usages:
if(await checkNetwork()){
print('connected to internet');
}
else{
print('disconnect');
}

Prince vishwakarma
- 21
- 2
-
But how you can listen if the network is changed? I have tried this way InternetAddress.lookup('google.com').asStream().listen((result) {}) But it doesn't work. – Miko Jul 12 '23 at 08:09
1
Use This Package https://pub.dev/packages/connectivity_plus
initialize the Connectivity result with a none at start.
ConnectivityResult _connectionStatus = ConnectivityResult.none;
final Connectivity _connectivity = Connectivity();
for stream, if the internet connect/disconnect in the middle of the app.
late StreamSubscription<ConnectivityResult> _connectivitySubscription;
Call that function from initstate
Future<void> initConnectivity() async {
late ConnectivityResult result;
try {
result = await _connectivity.checkConnectivity();
} on PlatformException catch (e) {
print(e);
return;
}
if (!mounted) {
return Future.value(null);
}
return _updateConnectionStatus(result);
}
_connectivitySubscription = _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
if (_connectionStatus == ConnectivityResult.mobile ||_connectionStatus==ConnectivityResult.wifi)
{
internet is available
}
else{not available}

Adil Shinwari
- 408
- 2
- 10