Blog-Image
  • Codeaamy
  • March 9, 2024

  • 0 Comments

Handle Internet Connectivity In Flutter With Riverpod

Getting data from Rest API making an HTTP request and displaying the data on the screen is the most basic and crucial task in an App. This process happens as the user is interacting with the application and an internet connection is required constantly to retrieve the data from the API.

If there is no internet connection chances are the app will keep showing the loading symbol and the user will think that the app is broken, or there is some bug in the app.

App developers must inform the user about Internet connectivity to help the user.

Here we will discuss how to check the internet connectivity of an app built in Flutter.

What are we going to Build?

For this, we will build a basic application which shows the internet connection status on the screen and a snack bar about the same. This will listen to the internet connection status so we get real-time network updates.

Let’s Get Started

Let’s start by creating a Flutter application which has a Text in the Center which says Connectivity Status and is Connected to internet Text. I have used a dark background but you can use whichever background colour you want.

Adding Pub Packages

For this application, we are going to use two packages.

  • connectivity_plus: A plugin which allows the Flutter app to discover network connectivity and configure the app accordingly.
  • flutter_riverpod: A state management library which helps to manage the state of the app and provide the dependencies.

let’s start by adding these two packages to our application. To do so add the packages to pubspec.yaml file

dependencies:
  flutter:
    sdk: flutter
  connectivity_plus: ^3.0.2
  flutter_riverpod: ^2.1.1

Note: Do not forget to run flutter pub get after adding dependencies

Connectivity Status Notifier

let us create a Connectivity status Notifier file which will have all the code to notify the app about the network connection. We will create a class with the same name which extends to StateNotifier.

StateNotifier is a simple solution to control state in an immutable manner and is a recommended solution for managing state when using Provider and Riverpod.

When extending to StateNotifier we need to provide a Type for the StateNotifier. Let’s create an enum which will have the connectivity status which we will track the state of.

enum ConnectivityStatus { NotDetermined, isConnected, isDisonnected }

class ConnectivityStatusNotifier extends StateNotifier<ConnectivityStatus> {}

Listen to ConnectivityResult changes.

Add the following code to the ConnectivityStatusNotifier

 ConnectivityStatus? lastResult;
  ConnectivityStatus? newState;

  ConnectivityStatusNotifier() : super(ConnectivityStatus.isConnected) {
    if (state == ConnectivityStatus.isConnected) {
      lastResult = ConnectivityStatus.isConnected;
    } else {
      lastResult = ConnectivityStatus.isDisonnected;
    }
    lastResult = ConnectivityStatus.NotDetermined;
    Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      switch (result) {
        case ConnectivityResult.mobile:
        case ConnectivityResult.wifi:
          newState = ConnectivityStatus.isConnected;
          break;
        case ConnectivityResult.none:
          newState = ConnectivityStatus.isDisonnected;
          break;
      }
      if (newState != lastResult) {
        state = newState!;
        lastResult = newState;
      }
    });
  }

First, we create two nullable variables of type ConnectivityStatus named as lastState and newState. When the connectivity status changes we will update these variables.

Using the super constructor to listen to changes taking place in the connectivity status of the device. The Switch lets us check the connectivity status and then update the value to the newState variable that we have created on top.

State Notifier Provider

// Final Global Variable which will expose the state.
// Should be outside of the class. 

final connectivityStatusProviders = StateNotifierProvider((ref) {
  return ConnectivityStatusNotifier();
});

StateNotifierProvider is a provider that is used to listen to and expose a StateNotifier and is a Riverpods recommended solution for managing state which may change in reaction to users interaction.

This connectivityStatusProvider will help us to listen to the state which is exposed by ConnectivityStateNotifier.

UI

Now let’s create a UI where we can update the user about the connectivity changes that take place. Here I have used ConsumerWidget to get the notifier provider in the widget.

class HomeScreen extends ConsumerWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    var connectivityStatusProvider = ref.watch(connectivityStatusProviders);
   
    return Scaffold(
        backgroundColor: Colors.black54,
        appBar: AppBar(
          title: const Text(
            'Network Connectivity',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20.0,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text(
                'Connectivity Status',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(
                connectivityStatusProvider == ConnectivityStatus.isConnected
                    ? 'Is Connected to Internet'
                    : 'Is Disconnected from Internet',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 20.0,
                ),
              )
            ],
          ),
        ));
  }
}

Show snackbar

Now that we get the status of the connection let us show a snackbar which will update the user.

   WidgetsBinding.instance.addPostFrameCallback((_) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            connectivityStatusProvider == ConnectivityStatus.isConnected
                ? 'Is Connected to Internet'
                : 'Is Disconnected from Internet',
            style: const TextStyle(
              color: Colors.white,
              fontSize: 20.0,
            ),
          ),
          backgroundColor: connectivityStatusProvider ==
                  ConnectivityStatus.isConnected
              ? Colors.green
              : Colors.red,
        ),
      );
    });

Updating the main.dart.

Whenever we use RiverPod we have wrap our app with ProviderScope so that widgets are able to read the Provider that we create.

// main.dart

void main() {
  runApp(ProviderScope(child: NetworkConnectivity()));
}

class NetworkConnectivity extends StatelessWidget {
  const NetworkConnectivity({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

That’s it. We have successfully created an application that updates the users when there is a change in the connectivity status of the device. Run the application on android, ios and try disconnecting and reconnecting the device to the internet.

Here is the complete code pushed to Github — network_connectivity_riverpod don’t forget to Like/Start the repo.

Thank You for reading my blog, if you have any doubts or recommendations please let me know in the comment section below. I would like to know what are the other way to globally listen to network connectivity.

You have 50 Claps per day. Claps do Motivate us to keep writing. Gotta Use Them All

Tags

Leave A Comment