Flutter | Check Connection Status in REALTIME

Hi there, In some situation, it is necessary to identify network status on user’s device so that we can show them different screens based on they are online or offline OR they are using mobile data or wifi

To do so, we are going to make use of the connectivity: package


add this package in pubspec.yaml file and get package

declare a variable in which we will assign value according to network conditions

String _networkStatus = "Unknown"

create an object of Connectivity class which can be imported using connectivity package

Connectivity _connectivity = Connectivity();

now declare stream subscription

StreamSubscription<ConnectivityResult> _connectivitySubscription;

create a function to make use of StreamSubscription

checkNet() {_connectivitySubscription =_connectivity.onConnectivityChanged.listen((status) {setState(() {if (status == ConnectivityResult.mobile) {setState(() => _connectionStatus = "Mobile");} else if (status == ConnectivityResult.wifi) {setState(() => _connectionStatus = "Wi-fi");} else if (status == ConnectivityResult.none) {setState(() => _connectionStatus = "No internet");}});});}

finally call this function inside initState()

@overridevoid initState() {super.initState();checkNet();}

make sure to cancel StreamSubscription

@overridevoid dispose() {super.dispose();_connectivitySubscription.cancel();}

and that’s all for this article