Home > Mobile >  Check internet connection status
Check internet connection status

Time:01-16

I'm looking for the best way to check if the device is connected to Internet from a Flutter iOS and Android app. connectivity_plus isn't enough, as stated in the officiale documentation:

Note that on Android, this does not guarantee connection to Internet. For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.

I also found an old question suggesting some "hand-made" workaround, but the thread is far too old as we are in 2023 now. Are there any new method to check for the connection status? How do you handle it in your apps?

CodePudding user response:

You can use the internet_connection_checker package in conjunction with connectivity_plus. The internet_connection_checker documentation mentions a simple example of how to do that here. This works by pinging a list of common DNS providers, and will work as expected if you're connected to WiFi that's not connected to the internet, like printer WiFi or a network that you haven't signed into. This way you don't have to deal with writing HTTP tests yourself!

Remember that it's still important to account for timeouts and bad connections, such as if you're connected to the internet but the server you're trying to reach is offline.

Side Note: The old question you linked to mentions data_connection_checker, which looks like an old version of internet_connection_checker. It isn't under active development (the last update was in 2019) so I wouldn't use it.

CodePudding user response:

Using the package internet_connection_checker you can check the connection status of devices (accurate for iOS/android I believe, and flaky for other stuff, so I just return true for other platforms in my code so that I don't miss a call because I assume they don't have connection when they actually do).

Here is an example implementation which you can call from anywhere in your code:

import 'dart:io' show Platform;

import 'package:internet_connection_checker/internet_connection_checker.dart';

abstract class INetworkInfo {
  Future<bool> get isConnected;
}

// Checks if the current device can connect to the internet (iOS and Android only).
class NetworkInfo implements INetworkInfo {
  final InternetConnectionChecker connectionChecker;

  NetworkInfo(this.connectionChecker);

  /// Returns TRUE if the current device has an internet connection. Returns FALSE if the device doesn't.
  ///
  /// Returns TRUE by default for platforms that aren't iOS or Android.
  @override
  Future<bool> get isConnected async => Platform.isAndroid || Platform.isIOS
      ? await connectionChecker.hasConnection
      : true;
}

Just call isConnected to check if you have a connection.

  • Related