Skip to content
Related Articles

Related Articles

How to Check Internet Connection in Flutter?

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 22 Mar, 2022
Improve Article
Save Article

In many applications, you need to check Internet Connection before going to Proceeds into the main screen. If the Internet connection is not available we can notify the user to Turn On the internet connection. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Create a class or a stateful widget  MyApp and return the MaterialApp(). In the home property of MaterialApp, give call the HomePage() class.

Dart




import 'package:checkinginternet/home.dart';
import 'package:flutter/material.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  State<MyApp> createState() => _MyAppState();
}
  
class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(debugShowCheckedModeBanner: false,
    home: HomePage(),);
  }
}


Now create another class Homepage, Where we are going to implement our actual logic.

Dart




import 'dart:io';
import 'package:flutter/material.dart';
  
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  
  @override
  State<HomePage> createState() => _HomePageState();
}
  
class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("GeeksforGeeks"),
      ),
      body: Column(
        children: [
          Text("Active Connection? $ActiveConnection"),
          const Divider(),
          Text(T),
          OutlinedButton(
              onPressed: () {
                CheckUserConnection();
              },
              child: const Text("Check"))
        ],
      ),
    );
  }
}


In the Homepage class, we have a Scaffold, body property containing the Column widget. The column has a Text and OutlinedButton widget, where we are calling a function CheckUserConnection. Now You have to define the function CheckUserConnection(), This Function going to async because it takes some time to check the internet connection.

Dart




bool ActiveConnection = false;
String T = "";
Future CheckUserConnection() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        setState(() {
          ActiveConnection = true;
          T = "Turn off the data and repress again";
        });
      }
    } on SocketException catch (_) {
      setState(() {
        ActiveConnection = false;
        T = "Turn On the data and repress again";
      });
    }
  }


We are just calling a lookup function with the passing string “google.com”. If the result is not empty we call the setstate() function, and change the variable Active Connection to true, other false, 

Note: If you are want to check on Application initiating, then you have to call the initState() function and inside call the CheckUserConnection Function.

Dart




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


The final code looks like,

Dart




import 'dart:io';
import 'package:flutter/material.dart';
  
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  
  @override
  State<HomePage> createState() => _HomePageState();
}
  
class _HomePageState extends State<HomePage> {
    bool ActiveConnection = false;
  String T = "";
  Future CheckUserConnection() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        setState(() {
          ActiveConnection = true;
          T = "Turn off the data and repress again";
        });
      }
    } on SocketException catch (_) {
      setState(() {
        ActiveConnection = false;
        T = "Turn On the data and repress again";
      });
    }
  }
 @override
  void initState() {
   CheckUserConnection();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("GeeksforGeeks"),
      ),
      body: Column(
        children: [
          Text("Active Connection? $ActiveConnection"),
          const Divider(),
          Text(T),
          OutlinedButton(
              onPressed: () {
                CheckUserConnection();
              },
              child: const Text("Check"))
        ],
      ),
    );
  }
}


Output:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!