Network handling using connectivity_plus in Flutter

Network handling using connectivity_plus in Flutter

For the areas of our program that significantly rely on the connection state, network connectivity is essential. As Flutter app experts, it is appropriate for us to properly manage those components of our application. By keeping an eye on the user’s internet connection, notifying them when there are problems with their connection, and, more crucially, triggering a mechanism that loads the necessary data when the connection is restored, we can provide the seamless experience we desire using connectivity_plus.

Using the Flutter package connectivity_plus, we can demonstrate how to handle the internet connection in the application in this article.

Add Dependencies

  • Add the following dependency in your pubspec.yaml

connectivity_plus:

In this article we can learn :

  • How to subscribe to the network changing events?
  • How to Update the widget when network changes?

Subscribe to the network event

Using Subscription, we can subscribe to the network change events :

Code :

String _networkStatus2 = ” “;
Connectivity connectivity = Connectivity();
StreamSubscription<ConnectivityResult> subscription;
@override
void initState() {
  super.initState();
  checkConnectivity2();
}
 
// Method2 - Using Subscription
void checkConnectivity2() async {
  // Subscribe to the connectivity change
  subscription =
      connectivity.onConnectivityChanged.listen(
    (ConnectivityResult result) {
    var conn = getConnectionValue(result);
// Show any dialog or snackbar here user can notice the network  
// connection
});
}

Using this You can listen to the network event and you can show dialog or snackbar to the user

Update widget by the internet connection

What if you want the app to automatically update widgets and listen for network changes throughout the app?

  • To accomplish this, we use the StreamProvider in the app’s root level to propagate changes throughout the app. We will use provider for this.
  • To manage it, let’s make a new class.
  • Navigate to the root widget from which you want to monitor changes.
  • Let’s go back to the main.dart file where we added this class.
  • When the connection changes, the widget will be update.

Note : For this we are using the package provider

Create a new Class Connectivity service. Create a constructor, add the value from the Connection change to the Stream Provider, which will cause the main widget to update

Full Code :

Main.dart

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:network_connectivity/network.dart';
import 'package:provider/provider.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return StreamProvider<ConnectivityResult>(
      create: (context) =>
          ConnectivityService().connectionStatusController.stream,
      initialData: ConnectivityResult.none,
      child: const MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Flutter Tutorials',
        home: ConnectivityDemo(),
      ),
    );
  }
}

network.dart

import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ConnectivityService {
  StreamController<ConnectivityResult> connectionStatusController =
      StreamController<ConnectivityResult>();
  ConnectivityService() {
    Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      connectionStatusController.add(result);
    });
  }
}

class ConnectivityDemo extends StatefulWidget {
  const ConnectivityDemo({super.key});

  final String title = "Connectivity Demo";
  @override
  ConnectivityDemoState createState() => ConnectivityDemoState();
}

class ConnectivityDemoState extends State<ConnectivityDemo> {
  String _networkStatus1 = '';
  String _networkStatus2 = '';
  String _networkStatus3 = '';
  Connectivity connectivity = Connectivity();
  StreamSubscription<ConnectivityResult>? subscription;
  @override
  void initState() {
    super.initState();
    checkConnectivity2();
  }
  // Method1
  void checkConnectivity1() async {
    var connectivityResult = await connectivity.checkConnectivity();
    var conn = getConnectionValue(connectivityResult);
    setState(() {
      _networkStatus1 = 'Check Connection:: $conn';
    });
  }
  // Method2 - Using Subscription
  void checkConnectivity2() async {
    // Subscribe to the connectivity change
    subscription =
        connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
      var conn = getConnectionValue(result);
      setState(() {
        _networkStatus2 = '<Subscription> :: $conn';
      });
    });
  }
  // Method3 - Using Providers
  void checkConnectivity3() async {
    var connectivityResult = Provider.of<ConnectivityResult>(context);
    var conn = getConnectionValue(connectivityResult);
    setState(() {
      _networkStatus3 = '<Provider> :: $conn';
    });
  }
  // Method to convert the connectivity to a string value
  String getConnectionValue(var connectivityResult) {
    String status = '';
    switch (connectivityResult) {
      case ConnectivityResult.mobile:
        status = 'Mobile';
        break;
      case ConnectivityResult.wifi:
        status = 'Wi-Fi';
        break;
      case ConnectivityResult.none:
        status = 'None';
        break;
      default:
        status = 'None';
        break;
    }
    return status;
  }
  @override
  Widget build(BuildContext context) {
    // Update widget whenever connection changes
    checkConnectivity3();
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        padding: const EdgeInsets.all(10.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Text(_networkStatus1),
            const SizedBox(height: 20.0),
            ElevatedButton(
              child: const Text('Check Connection'),
              onPressed: () {
                checkConnectivity1();
              },
            ),
            const SizedBox(height: 20.0),
            Text(_networkStatus2),
            const SizedBox(height: 20.0),
            Text(_networkStatus3),
            const SizedBox(height: 20.0),
          ],
        ),
      ),
    );
  }
}

Output

Conclusion

You can alert the user when there is a network connection problem by these steps. In Flutter, network connectivity is a crucial aspect of Flutter mobile app development as it allows the app to interact with remote servers and retrieve data. By utilizing various packages and APIs available in Flutter, developers can implement robust network connectivity features in their applications.

Ensuring a reliable network connection is essential for delivering a seamless user experience. Developers should handle scenarios where the device may have limited or no internet connectivity gracefully, providing appropriate feedback and error handling to users. Hence, in Flutter apps, developers can create responsive and efficient applications that can seamlessly communicate with servers, fetch data, and provide real-time updates to users.

Flutter Developers from Flutter Agency

Frequently Asked Questions (FAQs)

1. What does Flutter mean by connectivity?

With the support of this plugin, Flutter apps may find available network connectivity and set up their settings accordingly. It is able to distinguish between WiFi and cellular connections. But, this does not ensure an internet connection on Android.

2. How does Flutter handle network calls?

Enter your networking toolkit. Right-click and enter the name “ApiProvider” when creating a new Dart class. This is the primary API provider class for us, and it presently supports GET requests and some exception handling. If you need to add any extra methods, such as Post, Delete, or Put, for your particular application, do so.

3. How can I use Flutter to listen to network connectivity?

You must first add the connectivity plus plugin before you may manually check the internet connection by calling checkConnectivity or automatically monitor network connectivity changes by calling onConnectivityChanged.

Book Your Flutter Developer Now

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *

Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields