简体   繁体   中英

Check internet connection status

I'm looking for the best way to check if the device is connected to Inte.net 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 Inte.net. 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?

You can use the inte.net_connection_checker package in conjunction with connectivity_plus . The inte.net_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 inte.net, 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 inte.net 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 inte.net_connection_checker. It isn't under active development (the last update was in 2019) so I wouldn't use it.

Using the package inte.net_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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM