Flutter Internet Connectivity Checker

Flutter Internet :

Flutter Internet Connectivity is one of the important aspect to make sure your application can connect to internet and make network api calls and fetch data from server.

Some apps may need high speed internet to perform tasks like file uploads, video calls and other services which may use high amounts of internet.

So it is a good practice to check whether the device is connected to a WiFi or a mobile network before proceeding to the task.

Because WiFi internet is considered to be the fastest and comes with Unlimited data usages when compared to mobile networks which are also faster but limited.

If there is an interruption in network then it might be result in app crash or app may not respond to avoid these we need to make sure internet connection to avoid these issues.

So in this part of the tutorial we will check the status of flutter internet before and this scenario will be helpful in knowing the current status of internet.

Flutter Internet Checker Video Tutorial :

Go through the below tutorial for more detailed information

 

Project Structure :

This image depicts the usage of flutter internet connectivity checker

flutter internet connectivity

 

pubspec.yaml :

Add connectivity dependency to pubspec file and update the version

dev_dependencies:
  flutter_test:
    sdk: flutter
  connectivity: 0.4.9

 

main.dart :

Initialize with void main()

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

 

Enabling platform override for desktop

void _enablePlatformOverrideForDesktop() {
  if (!kIsWeb && (Platform.isWindows || Platform.isLinux)) {
    debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
  }
}

 

Return a material app and declare MyHomePage class with a title

MaterialApp(
  title: 'Flutter Demo',
  theme: ThemeData(
    primarySwatch: Colors.blue,
  ),
  home: MyHomePage(title: 'Flutter Home Page'),
);

 

MyHomePage class extending StatefulWidget and create a state

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

  final String title;

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

 

Declare a async method to check the flutter internet connectivity state using Future

Future<void> initConnectivity() async {
  ConnectivityResult result;
  try {
    result = await _connectivity.checkConnectivity();
  } on PlatformException catch (e) {
    print(e.toString());
  }

  if (!mounted) {
    return Future.value(null);
  }

  return _updateConnectionStatus(result);
}

 

Declare variables Connectivity, StreamSubscription

final Connectivity _connectivity = Connectivity();
StreamSubscription<ConnectivityResult> _connectivitySubscription;

 

Initialize variables in init() state

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

 

Check connectivity status of flutter internet and update

If mobile connected to WiFi then need to return

1) WiFi name,

2) BSSID,

3) IP Address

 

case ConnectivityResult.wifi:
  String wifiName, wifiBSSID, wifiIP;

  try {
    if (!kIsWeb && Platform.isIOS) {
      LocationAuthorizationStatus status =
      await _connectivity.getLocationServiceAuthorization();
      if (status == LocationAuthorizationStatus.notDetermined) {
        status =
        await _connectivity.requestLocationServiceAuthorization();
      }
      if (status == LocationAuthorizationStatus.authorizedAlways ||
          status == LocationAuthorizationStatus.authorizedWhenInUse) {
        wifiName = await _connectivity.getWifiName();
      } else {
        wifiName = await _connectivity.getWifiName();
      }
    } else {
      wifiName = await _connectivity.getWifiName();
    }
  } on PlatformException catch (e) {
    print(e.toString());
    wifiName = "Failed to get Wifi Name";
  }

  try {
    if (!kIsWeb && Platform.isIOS) {
      LocationAuthorizationStatus status =
      await _connectivity.getLocationServiceAuthorization();
      if (status == LocationAuthorizationStatus.notDetermined) {
        status =
        await _connectivity.requestLocationServiceAuthorization();
      }
      if (status == LocationAuthorizationStatus.authorizedAlways ||
          status == LocationAuthorizationStatus.authorizedWhenInUse) {
        wifiBSSID = await _connectivity.getWifiBSSID();
      } else {
        wifiBSSID = await _connectivity.getWifiBSSID();
      }
    } else {
      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 = '$result\n'
        'Wifi Name: $wifiName\n'
        'Wifi BSSID: $wifiBSSID\n'
        'Wifi IP: $wifiIP\n';
  });
  break;

 

If mobile connect to mobile network for internet

case ConnectivityResult.mobile:

 

or else if not connected in either case

case ConnectivityResult.none:

 

And finally declare default case if all the above steps failed

default:
  setState(() => _connectionStatus = 'Failed to get connectivity.');

 

FullCode :

Providing the full code for flutter internet checker implementation in you app.

import 'dart:async';
import 'dart:io';

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

void _enablePlatformOverrideForDesktop() {
  if (!kIsWeb && (Platform.isWindows || Platform.isLinux)) {
    debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
  }
}

void main() {
  _enablePlatformOverrideForDesktop();
  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 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<MyHomePage> {
  String _connectionStatus = 'Unknown';
  final Connectivity _connectivity = Connectivity();
  StreamSubscription<ConnectivityResult> _connectivitySubscription;

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

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

  Future<void> initConnectivity() async {
    ConnectivityResult result;
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      print(e.toString());
    }

    if (!mounted) {
      return Future.value(null);
    }

    return _updateConnectionStatus(result);
  }

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

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

        try {
          if (!kIsWeb && Platform.isIOS) {
            LocationAuthorizationStatus status =
            await _connectivity.getLocationServiceAuthorization();
            if (status == LocationAuthorizationStatus.notDetermined) {
              status =
              await _connectivity.requestLocationServiceAuthorization();
            }
            if (status == LocationAuthorizationStatus.authorizedAlways ||
                status == LocationAuthorizationStatus.authorizedWhenInUse) {
              wifiName = await _connectivity.getWifiName();
            } else {
              wifiName = await _connectivity.getWifiName();
            }
          } else {
            wifiName = await _connectivity.getWifiName();
          }
        } on PlatformException catch (e) {
          print(e.toString());
          wifiName = "Failed to get Wifi Name";
        }

        try {
          if (!kIsWeb && Platform.isIOS) {
            LocationAuthorizationStatus status =
            await _connectivity.getLocationServiceAuthorization();
            if (status == LocationAuthorizationStatus.notDetermined) {
              status =
              await _connectivity.requestLocationServiceAuthorization();
            }
            if (status == LocationAuthorizationStatus.authorizedAlways ||
                status == LocationAuthorizationStatus.authorizedWhenInUse) {
              wifiBSSID = await _connectivity.getWifiBSSID();
            } else {
              wifiBSSID = await _connectivity.getWifiBSSID();
            }
          } else {
            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 = '$result\n'
              'Wifi Name: $wifiName\n'
              'Wifi BSSID: $wifiBSSID\n'
              'Wifi IP: $wifiIP\n';
        });
        break;
      case ConnectivityResult.mobile:
      case ConnectivityResult.none:
        setState(() => _connectionStatus = result.toString());
        break;
      default:
        setState(() => _connectionStatus = 'Failed to get connectivity.');
        break;
    }
  }
}

Show Buttons
Hide Buttons
Read previous post:
Flutter HTTP POST Request tutorial for beginners

  Flutter HTTP POST : Flutter HTTP POST request method is used to fetch the values from the api based...

Close