How to check if wi-fi has internet in the flutter app - flutter

How to check if connected wi-fi network has internet in the flutter app, when I use connectivityResult == ConnectivityResult.wifi from connectivity 3.0.6 package, it returns true, but the upcoming functionalities won't work if I disabled the wi-fi data connection.

You can check the connection to a web page to make sure you have an internet connection, something like this :
checkConnection() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
setState(() {
con = true;
});
}
} on SocketException catch (_) {
setState(() {
con = false;
});
}
}
that's work for me good luck.

Related

How to check network connectivity in Flutter?

I want to check if user has internet connection and want it to be dynamic. Customisable messages will be shown to user according to it.
ElevatedButton(
onPressed: () async {
ans = await InternetConnectionChecker().hasConnection;
print(ans);
},
child: const Text('Fetch Data'),
),
I can check it when clicked on the button by the user but I want it to be automatic when user hops on the home page.
I tried putting
ans = await InternetConnectionChecker().hasConnection;
print(ans);
in initState but it doesn't work. Any suggestions as to how should I improve it?
EDIT :
I tried the first solution and on click of a button I get all the results perfectly
onPressed: () async {
var connectivityResult = await (Connectivity().checkConnectivity());
var subscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) {
print("Changed to $result");
});
if (connectivityResult == ConnectivityResult.mobile) {
// I am connected to a mobile network.
print("Mobile");
} else if (connectivityResult == ConnectivityResult.wifi) {
// I am connected to a wifi network.
print("Wifi");
}
},
It shows none when no internet is there. To mobile when connected to mobile hotspot and wifi when connected to wifi network.
But my issue still remains that I want to check internet connection when a user comes to my home page.
I tried this :
var subscription;
#override
initState() async {
super.initState();
print("hlo");
var connectivityResult = await (Connectivity().checkConnectivity());
var subscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) {
print("Changed to $result");
});
}
But this doesn't work. What am I dooing wrong? Can i improve this?
This plugin allows Flutter apps to discover network connectivity and configure themselves accordingly. It can distinguish between cellular vs WiFi connection. check here
connectivity_plus 3.0.2
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.
}
You can use connectivity_plus package to check internet connection. The http package that we use to call api can't tell if we don't have internet or the server is down.
class NetworkConnectivity {
NetworkConnectivity._();
static final _instance = NetworkConnectivity._();
static NetworkConnectivity get instance => _instance;
final _networkConnectivity = Connectivity();
final _controller = StreamController.broadcast();
Stream get myStream => _controller.stream;
// 1.
void initialise() async {
ConnectivityResult result = await _networkConnectivity.checkConnectivity();
_checkStatus(result);
_networkConnectivity.onConnectivityChanged.listen((result) {
print(result);
_checkStatus(result);
});
}
// 2.
void _checkStatus(ConnectivityResult result) async {
bool isOnline = false;
try {
final result = await InternetAddress.lookup('example.com');
isOnline = result.isNotEmpty && result[0].rawAddress.isNotEmpty;
} on SocketException catch (_) {
isOnline = false;
}
_controller.sink.add({result: isOnline});
}
void disposeStream() => _controller.close();
}
You can use the following guide: Flutter Internet Connectivity

How to connect Wi-Fi Network to Access Internet Connectivity using Flutter App?

I have created a flutter app which get list of available wi-fi networks using wifi_scan package,
and I get all available networks successfully.
below is code to get scanned results.
List<WiFiAccessPoint> accessPoints = <WiFiAccessPoint>[];
Future<void> _getScannedResults(BuildContext context) async {
if (await _canGetScannedResults(context)) {
// get scanned results
final results = await WiFiScan.instance.getScannedResults();
setState(() => accessPoints = results);
}
}
Future<bool> _canGetScannedResults(BuildContext context) async {
if (shouldCheckCan) {
// check if can-getScannedResults
final can = await WiFiScan.instance.canGetScannedResults();
// if can-not, then show error
if (can != CanGetScannedResults.yes) {
if (mounted) kShowSnackBar(context, "Cannot get scanned results: $can");
accessPoints = <WiFiAccessPoint>[];
return false;
}
}
return true;
}
As above code I get list of Wi-Fi networks in my flutter app.
Then I connect the network using plugin_wifi_connect Package.
The Connect Code as below.
ElevatedButton(
onPressed: () {
connect(
accessPoint.ssid.isNotEmpty ? accessPoint.ssid : "",
);
},
child: const Text("Connect"),
)
connect(String accessPoint) async {
var val = await PluginWifiConnect.connectToSecureNetwork(
accessPoint, "123456789",
isWep: false, isWpa3: false, saveNetwork: true);
}
As above code I connected to network successfully, but here is one problem which I connected to network but it cannot provide internet connectivity.
So please anyone can help me to How to Connect Android Device to Wi-fi Network for using internet connection to these device using this App?

how to indicate the user to activate the internet in flutter?

How to add this feature in Facebook Lite to the Flutter application, where this message appears when the Internet is cut off?
See the image below show image
**
Addition :
Suggest me to add the package connectivity_plus
But Can this package know if Wi-Fi or data are activated, but there is no internet, so the message that there is no internet appears?
With this package https://pub.dev/packages/connectivity_plus
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
showDialog();
}
or you setup a listener and watch yor connectivitiy changes
subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
// Got a new connectivity status!
})
Import connectivity_plus package and use below code.
import 'package:connectivity_plus/connectivity_plus.dart';
import 'dart:io';
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult != ConnectivityResult.mobile && connectivityResult != ConnectivityResult.wifi) {
//Internet is not connected
} else {
// Internet is connected
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
}
} on SocketException catch (_) {
print('not connected');
}
}

how to detect connection in flutter

so i have this function which detect if there is connection or not . if yes the var activeConnection is true else false . So if the connection is working i'm going to call a method sendEmail() which work with the plugin mailer . My problem is when i activated the WIFI it can send the email then if i turn it off an exception is shown
E/flutter ( 5347): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)]
Unhandled Exception: SocketException: Failed host lookup:
'smtp.gmail.com' (OS Error: No address associated with hostname, errno
= 7)
in this case activeConnection is true but when it try to send the email it can't find the connection . if i turn off the wifi and wait for a moment before i send the email it can detect that there is no wifi so i tried to add a sleep function before it check the connection but i'm facing the same problem .
this is the code :
Future checkUserConnection() async {
try {
//sleep(const Duration(seconds: 10));
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
setState(() {
activeConnection = true;
print(activeConnection);
});
}
} on SocketException catch (_) {
setState(() {
activeConnection = false;
print(activeConnection);
});
}
//print(activeConnection);
}
and this is where i call my function
onTap: () {
checkUserConnection();
print(activeConnection);
if (activeConnection) {
sendEmail();
ScaffoldMessenger.of(context).showSnackBar(showSnackBar(
false, "email sended ", Icons.error_outline));
} else {
ScaffoldMessenger.of(context).showSnackBar(showSnackBar(
true,
"check your internet connection !!!",
Icons.error_outline));
}
print("hello");
},
You have to make async function like this:
Future<bool> checkUserConnection() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return true;
}
} on SocketException catch (_) {
return false;
}
}
After that onTap() you have to code like this:
onTap: () {
checkUserConnection().then((activeConnection){
if (activeConnection) {
sendEmail();
ScaffoldMessenger.of(context).showSnackBar(showSnackBar(
false, "email sended ", Icons.error_outline));
} else {
ScaffoldMessenger.of(context).showSnackBar(showSnackBar(
true, "check your internet connection !!!",
Icons.error_outline));
}
});
}

facing issue in method channel internet connectivity in unit testing in flutter

I have checked internet connectivity in flutter while calling api in store class like this using 'connectivity' library.
Future<bool> callApi() async {
final isInternet = await Util.checkInternetAndShowDialog(context);
if (isInternet) {
final future = _repository.callApi();
var res = await future;
return true;
}
return false;
}
In Util class network connectivity is been checked like this::
class Util {
static Future<bool> checkInternetAndShowDialog(BuildContext context) async{
var internet = await NetworkConnectivity.rechability();
if (internet == false) {
AlertMessage().showAlertDialog(context, 'error message');
}
return internet;
}
}
In NetworkConnectivity class network connectivity is been checked using Connectivity library.
class NetworkConnectivity {
static Future<bool> rechability() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
return true;
}
return false;
}
}
my test cases code is like below:
test('call api successfully', () async {
when(mockStore.callApi()).thenAnswer((realInvocation) => Future.value());
expect(await store.callApi(), true);
});
so while writing unit testing I am facing error of connectivity and method channel.
connectivity error image
Can any one help please me how I can mock for internet connectivity in unit testing and pass the test in flutter. I shall be thankful for this.