Flutter: Check Internet Connection without any plugins

Last updated on March 3, 2022 A Goodman Loading... 4 comments

If your application needs an internet connection in order to work correctly then it is necessary to check the internet connection. For example, when there is a connection problem, a message will be displayed to alert the user of the situation. This article will show you how to do that in Flutter without using any plugin.

The Strategy

Our approach is to use the InternetAddress class of dart:io. It ships the static lookup() method, that can look up a host and return a list of internet addresses related to this host if the connection exists, like this:

[
  InternetAddress('some-ipv6-address', IPv6),   
  InternetAddress('some-ipv6-address', IPv6), 
  InternetAddress('some-ipv4-address', IPv4), 
  InternetAddress('some-ipv4-address', IPv4)
]

If there’s a problem with the connection, you will see an error message similar to this:

SocketException: Failed host lookup: 'kindacode.com' (OS Error: nodename nor servname provided, or not known, errno = 8)

A Complete Example

Preview

The small app we are going to build has a floating button and displays some text in the center of the screen. When the app starts, the Internet connection will be automatically checked. You can also manually check the network connection by clicking the floating button.

Here’s how it works:

Code & Explanations

This function is used to check the internet connection. It is triggered when the floating button is pressed or called by initState():

Future<void> _checkInternetConnection() async {
    try {
      final response = await InternetAddress.lookup('www.kindacode.com');
      if (response.isNotEmpty) {
        setState(() {
          _isConnected = true;
        });
      }
    } on SocketException catch (err) {
      setState(() {
        _isConnected = false;
      });
      if (kDebugMode) {
        print(err);
      }
    }
}

We call the function above in the initState() method to check whether the device is connected to the internet at the beginning:

@override
  void initState() {
    _checkInternetConnection();
    super.initState();
}

The full code:

// main.dart
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'dart:io';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

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

class _HomePageState extends State<HomePage> {
  bool? _isConnected;

  // This function is triggered when the floating button is pressed
  Future<void> _checkInternetConnection() async {
    try {
      final response = await InternetAddress.lookup('www.kindacode.com');
      if (response.isNotEmpty) {
        setState(() {
          _isConnected = true;
        });
      }
    } on SocketException catch (err) {
      setState(() {
        _isConnected = false;
      });
      if (kDebugMode) {
        print(err);
      }
    }
  }

  // This will check the connection at the beginning
  @override
  void initState() {
    _checkInternetConnection();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Kindacode.com'),
      ),
      body: Center(
        child: Text(_isConnected == true ? 'Connected' : 'Not Connected',
            style: const TextStyle(fontSize: 24)),
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: _checkInternetConnection, child: const Icon(Icons.info)),
    );
  }
}

References and Alternatives

In order to get more information about the InternetAddress class, please check the official docs. It’s also fine if you try to send an HTTP request by using the HTTPRequest class instead of looking up a host.

If you don’t want to use self-written code, there’s also a popular plugin named connectivity that helps you to discover network connectivity and configure themselves accordingly. It can distinguish between cellular vs WiFi connections.

Conclusion

This article demonstrated how to test internet connectivity in Flutter apps without using any third-party packages. If you would like to learn more interesting stuff, take a look at the following:

You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
4 Comments
Inline Feedbacks
View all comments
lopes
lopes
11 months ago

perfect!

Slim Ouadahi
Slim Ouadahi
11 months ago

Simple and efficient, thx 8)

Vishal
Vishal
1 year ago

This perfectly works. Thank You !

Related Articles