Eine reine Dart-Bibliothek, die über das Öffnen eines Sockets zu einer Liste von angegebenen Adressen die Internetverbindung überprüft, wobei jeder Adresse ein individueller Port und Timeout zugewiesen werden kann. Für Komfort werden Standardwerte bereitgestellt.
Aus öffentlichen Paketdaten erstellte Orientierung.
Eine reine Dart-Bibliothek, die die Internetverbindung ermittelt, indem sie versucht, Sockets zu einer konfigurierbaren Liste von Adressen mit benutzerdefinierten Ports und Timeouts zu öffnen. Sie bietet Standard-Einstellungen für eine schnelle Einrichtung, ermöglicht aber auch feinabgestimmte Kontrolle. Ideal für Apps, die eine zuverlässige Netzwerkstatus-Erkennung benötigen, ohne auf plattformspezifische APIs angewiesen zu sein. Die Bibliothek arbeitet asynchron und ist leichtgewichtig, wodurch sie sich besonders gut für die Echtzeit-Verbindungsüberwachung in Flutter-Anwendungen eignet.
Anwendungsfälle
Überprüfung der Internetverfügbarkeit vor API-Aufrufen
Überwachung des Netzwerkstatus in Hintergrundaufgaben
Verbindung vor der Daten-Synchronisierung überprüfen
Implementierung der Offline-Modus-Logik
Benutzerfeedback zum Verbindungsstatus bereitstellen
Hauptmerkmale
Socket-basierte Verbindungsprüfungen
Konfigurierbare Host-Adressen und -Ports
Anpassbare Timeout-Einstellungen
Standardkonfigurationen für eine einfache Nutzung
Asynchrone Operation mit Callbacks
Geeignet für
Flutter-Apps, die eine starke Netzwerkerkennung erfordern
Apps mit häufigen Netzwerkanfragen
Entwickler, die konsistente Querplattformen suchen
Anwendungen, die eine präzise Steuerung von Verbindungstests benötigen
Projekte, die plattformspezifischen Code vermeiden
Hinweise
Benötigt Internetzugang, um korrekt zu funktionieren
Kann bei vorübergehenden Netzwerkproblemen falsch-negative Ergebnisse auslösen
Überprüft die tatsächliche Internet-Erreichbarkeit über die Socket-Verbindung hinaus nicht
Beschränkt auf TCP-Verbindungsprüfungen
Keine integrierten Wiederholungsmechanismen
Original-README
Originaler README-Schnappschuss aus dem verknüpften Quell-Repository. Aktuelle Inhalte finden Sie im Repository.
data_connection_checker
A pure Dart utility library that checks for an internet connection by opening a socket to a list of specified addresses, each with individual port and timeout. Defaults are provided for convenience.
Note that this plugin is in beta and may still have
a few issues. Feedback is welcome.
Checks for an internet (data) connection, by opening a socket to a list of addresses.
The defaults of the plugin should be sufficient to reliably determine if
the device is currently connected to the global network, e.i. has access to the Internet.
Note that you should not be using the current network status for deciding whether you can reliably make a network connection. Always guard your app code against timeouts and errors that might come from the network layer.
Quick start
DataConnectionChecker() is actually a Singleton. Calling DataConnectionChecker()
is guaranteed to always return the same instance.
You can supply a new list to DataConnectionChecker().addresses if you
need to check different destinations, ports and timeouts.
Also, each address can have its own port and timeout.
See InternetAddressCheckOptions in the docs for more info.
First you need to install it (this is the preferred way)
Then you can start using the library:
bool result = awaitDataConnectionChecker().hasConnection;
if(result == true) {
print('YAY! Free cute dog pics!');
} else {
print('No internet :( Reason:');
print(DataConnectionChecker().lastTryResults);
}
Purpose
The reason this package exists is that connectivity package cannot reliably determine if a data connection is actually available. More info on its page here: https://pub.dev/packages/connectivity
You can use this package in combination with connectivity in the following way:
var isDeviceConnected = false;
var subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) async {
if(result != ConnectivityResult.none) {
isDeviceConnected = awaitDataConnectionChecker().hasConnection;
}
});
Note: remember to properly cancel the subscription when it's no longer needed. See connectivity package docs for more info.
How it works
All addresses are pinged simultaneously. On successful result (socket connection to address/port succeeds) a true boolean is pushed to a list, on failure (usually on timeout, default 10 sec) a false boolean is pushed to the same list.
When all the requests complete with either success or failure, a check is made to see if the list contains at least one true boolean. If it does, then an external address is available, so we have data connection. If all the values in this list are false, then we have no connection to the outside world of cute cat and dog pictures, so hasConnection also returns false too.
This all happens at the same time for all addresses, so the maximum waiting time is the address with the highest specified timeout, in case it's unreachable.
I believe this is a reliable and fast method to check if a data connection is available to a device, but I may be wrong. I suggest you open an issue on the Github repository page if you have a better way of.
... is 10 seconds. Interval is the time between automatic checks. Automatic
checks start if there's a listener attached to onStatusChange, thus remember
to cancel unneeded subscriptions.
checkInterval (which controls how often a check is made) defaults
to this value. You can change it if you need to perform checks more often
or otherwise.
import'package:data_connection_checker/data_connection_checker.dart';
main() async {
// Simple check to see if we have internetprint("The statement 'this machine is connected to the Internet' is: ");
print(awaitDataConnectionChecker().hasConnection);
// returns a bool// We can also get an enum value instead of a boolprint("Current status: ${await DataConnectionChecker().connectionStatus}");
// prints either DataConnectionStatus.connected// or DataConnectionStatus.disconnected// This returns the last results from the last call// to either hasConnection or connectionStatusprint("Last results: ${DataConnectionChecker().lastTryResults}");
// actively listen for status updates// this will cause DataConnectionChecker to check periodically// with the interval specified in DataConnectionChecker().checkInterval// until listener.cancel() is calledvar listener = DataConnectionChecker().onStatusChange.listen((status) {
switch (status) {
caseDataConnectionStatus.connected:
print('Data connection is available.');
break;
caseDataConnectionStatus.disconnected:
print('You are disconnected from the internet.');
break;
}
});
// close listener after 30 seconds, so the program doesn't run foreverawaitFuture.delayed(Duration(seconds: 30));
await listener.cancel();
}
Note: Remember to dispose of any listeners,
when they're not needed to prevent memory leaks,
e.g. in aStatefulWidget's dispose() method:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Features and bugs
Please file feature requests and bugs at the issue tracker.