Flutter: Check Internet Connection without any plugins

Last updated on January 18, 2021 Guest Contributor Loading... Post a comment

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.

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 address 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 this error:

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

A Complete Example

Preview:

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;
      });
      print(err);
    }
  }

We also use 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 'dart:io';

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

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

class HomePage extends StatefulWidget {
  @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;
      });
      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: Text('Kindacode.com'),
      ),
      body: Center(
        child: Text(_isConnected == true ? 'Connected' : 'Not Connected',
            style: TextStyle(fontSize: 24)),
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: _checkInternetConnection, child: 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 connection.

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: Load and display content from CSV files, Flutter: Set an image Background for the entire screen, 3 Ways to create Random Colors in Flutter, Write a simple BMI Calculator with Flutter.

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

Related Articles

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x