Flutter Connectivity

Flutter Connectivity:

In Flutter, Flutter Apps discovers network connectivity and configures automatically themselves accordingly. It also distinguishes the connection whether it is cellular or WiFi connection type. The connectivity class from this plugin works well for both Android and IOS.

Important: Note that on Android, this does not guarantee connection to the Internet. For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.

Below is the sample code to check the current status:

 

import 'package:connectivity/connectivity.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.
}

In the above code, it shows that the device is connected to a WiFi network

Important: Note that you should not be using the current network status for deciding whether you can reliably make a network connection. Always secure your app code against timeouts and errors that might come from the network layer.

You can also listen for network state changes by subscribing to the stream that is exposed by connectivity plugin.

As shown in below sample code:

import 'package:connectivity/connectivity.dart';

@override
initState() {
super.initState();

subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
// Got a new connectivity status!
})
}

// Be sure to cancel the subscription after you are done
@override
dispose() {
super.dispose();

subscription.cancel();
}

Adding the dependency package :

Add the dependency package to pubspec.yaml file using below code.

dependencies:

connectivity: ^0.4.3+1

After adding the dependency package run the get package method to import all the dependencies.

Import the package into your dart code:

Use the below code to import the package into your dart code.

import 'package:connectivity/connectivity.dart';

After importing the dependency package run the get dependencies method to import all the required dependencies into your dart file. without importing if we use it will show file not found exception or error.

Below is the complete example code for Flutter Connectivity:

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:connectivity/connectivity.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
String _connectionStatus = 'Unknown';
final Connectivity _connectivity = Connectivity();
StreamSubscription _connectivitySubscription;

@override
void initState() {
super.initState();
initConnectivity();
_connectivitySubscription =
_connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
}

@override
void dispose() {
_connectivitySubscription.cancel();
super.dispose();
}

// Platform messages are asynchronous, so we initialize in an async method.
Future initConnectivity() async {
ConnectivityResult result;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await _connectivity.checkConnectivity();
} on PlatformException catch (e) {
print(e.toString());
}

// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) {
return;
}

_updateConnectionStatus(result);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(child: Text('Connection Status: $_connectionStatus')),
);
}

Future _updateConnectionStatus(ConnectivityResult result) async {
switch (result) {
case ConnectivityResult.wifi:
String wifiName, wifiBSSID, wifiIP;

try {
wifiName = await _connectivity.getWifiName();
} on PlatformException catch (e) {
print(e.toString());
wifiName = "Failed to get Wifi Name";
}

try {
wifiBSSID = await _connectivity.getWifiBSSID();
} on PlatformException catch (e) {
print(e.toString());
wifiBSSID = "Failed to get Wifi BSSID";
}

try {
wifiIP = await _connectivity.getWifiIP();
} on PlatformException catch (e) {
print(e.toString());
wifiIP = "Failed to get Wifi IP";
}

setState(() {
_connectionStatus = '$resultn'
'Wifi Name: $wifiNamen'
'Wifi BSSID: $wifiBSSIDn'
'Wifi IP: $wifiIPn';
});
break;
case ConnectivityResult.mobile:
case ConnectivityResult.none:
setState(() => _connectionStatus = result.toString());
break;
default:
setState(() => _connectionStatus = 'Failed to get connectivity.');
break;
}
}
}

Congratulations You Have Learned Connecting WiFi Devices In Flutter ….!!!

If It Is Helpful Share It With Your Friends….!!!

Leave a Reply

Categories