搜索插件、代码仓与 APP 分类

插件详情v3.0.1

internet_connection_checker

一个专为无缝互联网连接检查而设计的库。此库可帮助您验证互联网连接并检测网络速度缓慢的情况。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
8.7万
喜欢数
1340
Pub 分数
150

安装插件

flutter pub add internet_connection_checker

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

互联网连接检查器包提供了一种简单可靠的方法,可在多个平台上检查互联网连接状态。它允许开发者检测设备是否连接到互联网,并识别慢速连接状况,使应用程序能够相应地响应——例如显示离线状态或调整行为。该库在设计时就考虑了跨平台支持,可在 Android、iOS、Web、macOS、Windows 和 Linux 上无缝运行。该库使用高效的后台检查机制,在确保实时更新的同时最大限度地减少电池消耗。

适合场景

  • 在 API 调用前检查在线状态
  • 显示网络状态指示器
  • 根据连接速度调整应用行为
  • 优雅地处理离线场景
  • 在长时间运行的任务期间监控连接性

主要特点

  • 实时连接监控
  • 支持检测慢速连接
  • 跨平台兼容性
  • 轻便高效
  • 简单的 API 与事件流
  • 自动重连检测

适合对象

  • 需要可靠网络状态感知的应用程序
  • 离线优先的应用程序
  • 依赖网络的功能,如同步或流媒体
  • 面向多个平台的开发者
  • 需要连接性响应式UI反馈的应用程序

使用建议

  • 某些平台可能需要权限
  • 如果管理不当,背景检查可能会影响电池寿命
  • 不处理代理或防火墙配置
  • 仅限连接检测,不包括数据传输验证
  • 不适用于高频轮询,除非进行节流

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

🌍 Internet Connection Checker

Dart CI codecov style: very good analysis License: BSD 3-Clause

A library designed for seamless internet connectivity checks. This library enables you to verify your internet connection and can also detect slow internet connectivity.

Table of contents

Usecases of this library:

  • Backend Server Checks: Seamlessly verify internet connectivity and server reachability using built-in default addresses or by configuring custom backend server URLs tailored to your application needs.

  • Slow Internet Detection: Efficiently detect and manage slow internet connections on the user's device to ensure a smooth user experience.

  • Auto Refresh: Automatically refresh pages in your app when the internet becomes available, providing a dynamic and seamless user experience.

    For detailed implementation, refer to the example files:

    example/lib/blocs/fetch_todos_cubit.dart
    example/lib/pages/auto_refresh_when_network_is_available_page.dart
    
💡 Important Note

To prevent memory leaks, always dispose of the InternetConnectionChecker instance when it's no longer needed. For example, in a StatefulWidget's dispose method:

@override
void dispose() {
  connectionChecker.dispose(); // Dispose of the InternetConnectionChecker instance
  super.dispose();
}

Description

Checks for an internet (data) connection, by checking accessible Uri's.

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.

Platform Support
Android iOS MacOS Web Linux Windows
✅ ✅ ✅ ✅ ✅ ✅

Demo

Demo

Quick start

Add the following dependencies to your pubspec.yaml:

dependencies:
  internet_connection_checker: ^2.0.0

Android Configuration

On Android, for correct working in release mode, you must add INTERNET & ACCESS_NETWORK_STATE permissions to AndroidManifest.xml, follow the next lines:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
    
    <!-- Permissions for internet_connection_checker -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    
    <application
        ...

Mac OS Configuration

On MacOS, you'll need to add the following entry to your DebugProfile.entitlements and Release.entitlements (located under macos/Runner) to allow access to internet.

  <key>com.apple.security.network.server</key>
  <true/>

Example:

  <plist version="1.0">
    <dict>
	    <key>com.apple.security.app-sandbox</key>
	    <true/>
    </dict>
  </plist>

Purpose

The reason this package exists is that connectivity_plus package cannot reliably determine if a data connection is actually available. More info on its page here: https://pub.dev/packages/connectivity_plus.

Getting Started

The InternetConnectionChecker can be used as a singleton or can be instantiated with a custom instance with your curated AddressCheckOption's.

Best usage with Flutter Bloc/Cubit

The InternetConnectionChecker package is particularly useful in scenarios where you need to handle changes in network connectivity dynamically. For instance, you can use it to refresh the page or trigger specific actions when the device goes offline and then reconnects to the internet. This is useful for applications where real-time updates or data synchronization is critical.

See example folder for one specific example which illustrates how to retry page refresh when internet connection is available. The example files paths are listed below:

example/lib/blocs/fetch_todos_cubit.dart
example/lib/pages/auto_refresh_when_network_is_available_page.dart
Singleton Basic Usage example
import 'package:internet_connection_checker/internet_connection_checker.dart';

void main() async {
  final bool isConnected = await InternetConnectionChecker.instance.hasConnection;
  if (isConnected) {
    print('Device is connected to the internet');
  } else {
    print('Device is not connected to the internet');
  }
}

Listen to Stream for Internet Connection availability changes:
import 'package:internet_connection_checker/internet_connection_checker.dart';

void main() {
  final connectionChecker = InternetConnectionChecker.instance;

  final subscription = connectionChecker.onStatusChange.listen(
    (InternetConnectionStatus status) {
      if (status == InternetConnectionStatus.connected) {
        print('Connected to the internet');
      } else {
        print('Disconnected from the internet');
      }
    },
  );

  // Remember to cancel the subscription when it's no longer needed
  subscription.cancel();
}

Note: Remember to dispose of any listeners and the instance of InternetConnectionChecker, when they're not required to prevent memory leaks. e.g. in a StatefulWidget's dispose() method:

...
@override
void dispose() {
  listener.cancel();
  connectionChecker.dispose();
  super.dispose();
}
...
Creating a Custom Instance

To create a custom instance of InternetConnectionChecker with specific check options:

import 'package:internet_connection_checker/internet_connection_checker.dart';

void main() async {
  final customChecker = InternetConnectionChecker.createInstance(
    addresses: [
      AddressCheckOption(uri: Uri.parse('https://api.github.com/users/octocat')),
      AddressCheckOption(
        uri: Uri.parse('https://api.agify.io/?name=michael'),
      ),
    ],
  );

  bool isConnected = await customChecker.hasConnection;
  print('Custom instance connected: $isConnected');
}

Note: Remember to dispose of InternetConnectionChecker instance, when it's not needed to prevent memory leaks, e.g. in a StatefulWidget's dispose() method:

...
@override
void dispose() {
  super.dispose();
  customChecker.dispose();
}
...
Enable detection for slow internet connectivity

To create a custom instance of InternetConnectionChecker with detection for slow internet connectivity:

import 'package:internet_connection_checker/internet_connection_checker.dart';

void main() async {
  final customChecker = InternetConnectionChecker.createInstance(
    slowConnectionConfig: SlowConnectionConfig(
        enableToCheckForSlowConnection: true,
        slowConnectionThreshold: const Duration(seconds: 1),
      ),
  );

  bool isConnected = await customChecker.hasConnection;
  print('Custom instance connected: $isConnected');
}

Note: Ensure your slowConnectionThreshold's duration is not more than the checkInternal and checkTimeout Duration.

Using requireAllAddressesToRespond

To ensure that the internet connection status is marked as connected only when all specified addresses are reachable, you can enable the requireAllAddressesToRespond configuration.

import 'package:internet_connection_checker/internet_connection_checker.dart';

void main() async {
  // Create a custom instance with requireAllAddressesToRespond set to true
  /// Remember to dispose of [customChecker] instance, when it's not needed 
  /// to prevent memory leaks.
  final customChecker = InternetConnectionChecker.createInstance(
    requireAllAddressesToRespond: true,
    addresses: [
      AddressCheckOption(uri: Uri.parse('https://dummyapi.online/api/movies/1')),
      AddressCheckOption(
        uri: Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
      ),
    ],
  );

  // Check connectivity
  final bool isConnected = await customChecker.hasConnection;

  if (isConnected) {
    print('All specified backend servers are reachable.');
  } else {
    print('Not all specified backend servers are reachable.');
  }
}

See example folder for more examples.

Features and bugs

Please file feature requests and bugs at the issue tracker.

Credits

Web platform support for this package has been inspired by the internet_connection_checker_plus library.

所属分类

依赖

依赖清单 3 项

源码仓库

使用此插件的项目