Flutter Check Internet Connection Tutorial – Internet Connectivity Guide Flutter

Haris Bin Nasir Avatar

·

·

In this guide, we’ll show you how to check whether your Flutter application is connected to the internet. This method works for all deployment targets, including web, mobile, and desktop. We’ll build a simple application to detect the device’s internet connection status and update the UI accordingly.

If you prefer watching a video tutorial here is a link to that.

Setting Up the Project

Creating an Empty Project

First, create a new Flutter project. If Flutter is already installed, use the following commands:

flutter create internet_checker

This will generate a new Flutter project with the necessary files and folders. Navigate into the project directory to start building the application.

cd internet_checker

Implementing Internet Connectivity Check

Adding Dependencies

Add the internet_connection_checker_plus dependency in your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  internet_connection_checker_plus: ^0.1.0

To dowload the dependency click here.

Run flutter pub get to install the package. This package helps in monitoring the internet connection status seamlessly across various platforms.

flutter pub get
Modifying Android Manifest

For Android, you need to add internet permission. Open android/app/src/main/AndroidManifest.xml and add the following above the <application> tag:

<uses-permission android:name="android.permission.INTERNET"/>

This permission is required for the app to access the internet, allowing it to check the connection status.

Initializing the HomePage Widget
Creating a Stateful Widget

In the lib directory, create a new Dart file named homepage.dart. Define a stateful widget to represent our home page:

import 'dart:async';
import 'package:flutter/material.dart';
import 'internet_connection_checker_plus.dart';

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

  @override
  State<HomePage> createState() => _HomePageState();
}

Stateful widgets are essential for managing dynamic content and states within your app, making them perfect for this use case where the connection status might change.

Managing Internet Connection State

Add the following code to manage the internet connection state:

class _HomePageState extends State<HomePage> {
  bool isConnectedToInternet = false;

  StreamSubscription? _internetConnectionStreamSubscription;

  @override
  void initState() {
    super.initState();
    _internetConnectionStreamSubscription =
        InternetConnection().onStatusChange.listen((event) {
      switch (event) {
        case InternetStatus.connected:
          setState(() {
            isConnectedToInternet = true;
          });
          break;
        case InternetStatus.disconnected:
          setState(() {
            isConnectedToInternet = false;
          });
          break;
        default:
          setState(() {
            isConnectedToInternet = false;
          });
          break;
      }
    });
  }

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

In this code, the initState method subscribes to the internet connection status changes. When the status changes, it updates the isConnectedToInternet variable, triggering a UI update.

Building the UI

Update the build method to display the connection status:

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: SizedBox(
      width: MediaQuery.sizeOf(context).width,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(
            isConnectedToInternet ? Icons.wifi : Icons.wifi_off,
            size: 50,
            color: isConnectedToInternet ? Colors.green : Colors.red,
          ),
          Text(
            isConnectedToInternet
                ? "You are connected to the internet."
                : "You are not connected to the internet.",
          ),
        ],
      ),
    ),
  );
}

This widget uses a Column to center an icon and text message on the screen, visually indicating the connection status with a green Wi-Fi icon when connected and a red Wi-Fi off icon when disconnected.

Setting HomePage as Home in main.dart

Open main.dart and set the HomePage widget as the home property in your MaterialApp:

import 'package:flutter/material.dart';
import 'homepage.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

By setting HomePage as the home widget, you ensure that this screen is the first one displayed when the app launches.

Running the Application

Now, you can run the application on a simulator or physical device:

flutter run

Running this command will start the Flutter application, allowing you to see the internet connectivity status in real-time.

Get Source Source for free:

Conclusion

In this tutorial, we demonstrated how to check the internet connectivity status in a Flutter application using the internet_connection_checker_plus package. This allows your app to respond dynamically to changes in network status, providing a better user experience. By following these steps, you can ensure your Flutter app can accurately detect and respond to changes in internet connectivity across all platforms.

Happy coding!

Leave a Reply

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