Check whether there is an Internet connection available on Flutter app

CodeWithFlutter
2 Min Read

To check whether there is an Internet connection available in a Flutter app, you can use the connectivity package. This package provides a simple API for determining the network connectivity state.

Here’s an example of how to use the connectivity package to check for an Internet connection in Flutter:

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  ConnectivityResult _connectivityResult;

  @override
  void initState() {
    super.initState();
    Connectivity().onConnectivityChanged.listen((result) {
      setState(() {
        _connectivityResult = result;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: _connectivityResult == ConnectivityResult.none
              ? Text('No Internet Connection')
              : Text('Internet Connection Available'),
        ),
      ),
    );
  }
}

In this example, the Connectivity class is used to listen for changes in the network connectivity state. The onConnectivityChanged stream is subscribed to, and the listen method is used to update the _connectivityResult field whenever the network connectivity state changes. The Text widget in the build method is used to display a message indicating whether or not there is an Internet connection available.

Note that this is just one way to check for an Internet connection in a Flutter app, and there are other approaches that can be used, such as using the dio package or using the HttpClient class. The method you choose will depend on your specific use case and requirements.

Share this Article
Leave a comment