Newby Coder header banner

Flutter Network Connectivity

Network connection status of Android/iOS device in Flutter

Using connectivity package, Flutter Apps can discover network connectivity and configure themselves accordingly

It also distinguishes whether connection is cellular or WiFi connection type

On Android, this does not guarantee connection to the Internet

For instance, an app might have wifi access but it might be a VPN or a hotel WiFi with no internet access


Creating new Flutter App

Check Flutter installation to setup Flutter

Use flutter create command to create a Flutter project (here network_connectivity_app:

flutter create network_connectivity_app

Dependency

Implementation

Import

import 'package:connectivity/connectivity.dart';

Check current status

import 'package:connectivity/connectivity.dart';
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
  // connected to a mobile network
}
else if (connectivityResult == ConnectivityResult.wifi) {
  // connected to a wifi network
}

Connectivity state listener

To listen for network state changes, subscribe to the stream which is exposed by connectivity plugin i.e. Connectivity().onConnectivityChanged

import 'package:connectivity/connectivity.dart';
@override
initState() {
  super.initState();
  subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
    // Received a new connectivity status
  })
}
// Cancel the subscription on dispose
@override
dispose() {
  super.dispose();
  subscription.cancel();
}

App Code

network_connectivity_app/lib/main.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:connectivity/connectivity.dart';

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

class ConnectivityStatusApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Connectivity Status App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ConnectivityStatusPage(title: 'Connectivity Status Page'),
    );
  }
}

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

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

class ConnectivityStatusPageState extends State<ConnectivityStatusPage> {
  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;
    }
    updateConnectionStatus(result);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Connectivity Example App'), ),
      body: Center(child: Text('Connectivity Status: $connectionStatus')),
    );
  }

  Future<void> 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 = '$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;
    }
  }
}

Run instructions

Ensure a supported device is connected or emulator/simulator is started

Go to project directory

Use flutter run command to run

flutter run

It builds and runs app on an available android/ios device


Screenshot/image

Android

cl-flutter-network-connectivity

iOS

cm-flutter-network-connectivity-as1cm-flutter-network-connectivity-as2