Home > database >  How to check network connectivity in Flutter?
How to check network connectivity in Flutter?

Time:11-01

I want to check if user has internet connection and want it to be dynamic. Customisable messages will be shown to user according to it.

ElevatedButton(
        onPressed: () async {
          ans = await InternetConnectionChecker().hasConnection;
          print(ans);
        },
        child: const Text('Fetch Data'),
      ),

I can check it when clicked on the button by the user but I want it to be automatic when user hops on the home page. I tried putting

ans = await InternetConnectionChecker().hasConnection;
          print(ans);

in initState but it doesn't work. Any suggestions as to how should I improve it?

EDIT : I tried the first solution and on click of a button I get all the results perfectly

onPressed: () async {
          var connectivityResult = await (Connectivity().checkConnectivity());
          var subscription = Connectivity()
              .onConnectivityChanged
              .listen((ConnectivityResult result) {
            print("Changed to $result");
          });
          if (connectivityResult == ConnectivityResult.mobile) {
            // I am connected to a mobile network.
            print("Mobile");
          } else if (connectivityResult == ConnectivityResult.wifi) {
            // I am connected to a wifi network.
            print("Wifi");
          }
        },

It shows none when no internet is there. To mobile when connected to mobile hotspot and wifi when connected to wifi network. But my issue still remains that I want to check internet connection when a user comes to my home page. I tried this :


    var subscription;
    @override
    initState() async {
      super.initState();
      print("hlo");

      var connectivityResult = await (Connectivity().checkConnectivity());
      var subscription = Connectivity()
          .onConnectivityChanged
          .listen((ConnectivityResult result) {
        print("Changed to $result");
      });
    }

But this doesn't work. What am I dooing wrong? Can i improve this?

CodePudding user response:

This plugin allows Flutter apps to discover network connectivity and configure themselves accordingly. It can distinguish between cellular vs WiFi connection. check here

connectivity_plus 3.0.2

import 'package:connectivity_plus/connectivity_plus.dart';

var connectivityResult = await (Connectivity().checkConnectivity()); 
if (connectivityResult == ConnectivityResult.mobile) {
// I am connected to a mobile network. }
else if (connectivityResult == ConnectivityResult.wifi) {
// I am connected to a wifi network. 
}

CodePudding user response:

You can use connectivity_plus package to check internet connection. The http package that we use to call api can't tell if we don't have internet or the server is down.

class NetworkConnectivity {
  NetworkConnectivity._();
  static final _instance = NetworkConnectivity._();
  static NetworkConnectivity get instance => _instance;
  final _networkConnectivity = Connectivity();
  final _controller = StreamController.broadcast();
  Stream get myStream => _controller.stream;
  // 1. 
  void initialise() async {
    ConnectivityResult result = await _networkConnectivity.checkConnectivity();
    _checkStatus(result);
    _networkConnectivity.onConnectivityChanged.listen((result) {
      print(result);
      _checkStatus(result);
    });
  }
// 2.
  void _checkStatus(ConnectivityResult result) async {
    bool isOnline = false;
    try {
      final result = await InternetAddress.lookup('example.com');
      isOnline = result.isNotEmpty && result[0].rawAddress.isNotEmpty;
    } on SocketException catch (_) {
      isOnline = false;
    }
    _controller.sink.add({result: isOnline});
  }
  void disposeStream() => _controller.close();
}

You can use the following guide: Flutter Internet Connectivity

  • Related