搜尋套件、儲存庫與 APP 分類

套件詳情v3.1.2

internet_connection_checker_plus

一個純 Dart 套件,即使在行動網路下也能以亞秒級回應時間檢查您的網路連接!

AndroidiOSWebmacOSWindowsLinux
近 30 天下載
21.2萬
喜歡數
536
Pub 分數
160

安裝套件

flutter pub add internet_connection_checker_plus

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

一個輕量級的純 Dart 套件,旨在跨多個平台快速且可靠地檢查互聯網連接。它提供亞秒級回應時間,非常適合需要立即獲取網路狀態反饋的即時應用。該套件可在 Android、iOS、Web、macOS、Windows 和 Linux 上順暢運行,無論環境為何,皆能提供一致行為。專為效能與簡易性設計,提供直觀的 API 來檢測線上或離線狀態,無需依賴平台特定程式碼。

適用情境

  • 即時應用狀態監控
  • 離線模式檢測
  • 登入期間的網路健康檢查
  • 基於連接性的動態UI更新
  • 背景連接輪詢

主要特色

  • 亞秒級回應時間
  • 跨平台相容性
  • 純 Dart 實現
  • 簡單直覺的 API
  • 低資源使用
  • 無原生依賴

適合對象

  • 需要快速網絡檢查的應用程式
  • 尋求輕量級解決方案的開發者
  • 針對多個平台的專案
  • 即時或反應式使用者介面
  • 需要可靠離線檢測的應用程式

使用建議

  • 不處理複雜的網路診斷
  • 依賴基本的可達性測試
  • 可能需要額外的邏輯來處理邊緣情況
  • 不適合進階網路分析
  • 僅限連接狀態,不限帶寬或品質

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

🧠 Created by the developer of Brink: Psychological Warfare

"Can you find the sweet spot between bold and delusional?"
Support the maintenance of this package by checking out my latest indie game!

Get it on Google Play   Download on the App Store


Internet Connection Checker Plus

pub package GitHub

An enterprise-grade network connectivity monitor for Dart and Flutter.

Standard network interfaces can verify local connections (like Wi-Fi router connectivity) but cannot guarantee actual internet reachability. This package proactively verifies external routing by checking reachability and response statuses against highly available global endpoints.

[!NOTE]

🚀 v3 is now available! It removes the connectivity_plus dependency to make this a pure Dart package. Please read the v3 Migration Guide to understand the breaking changes and how to update your project.

Features

  • Accurate Verification: Verifies real internet access instead of local network status.
  • High Performance: Designed for subsecond response times.
  • Real-Time Monitoring: Stream-based API for immediate connectivity status updates.
  • Extensible Architecture: Define custom endpoints, validation criteria, and networking clients.
  • Universal Compatibility: Natively supports both pure Dart environments and Flutter applications.

Permissions (Flutter)

When using this package in a Flutter application, ensure you have the appropriate network permissions enabled for your target platforms.

For detailed platform-specific network permission instructions, please refer to the Flutter Networking Documentation.

Usage

Basic Verification

Check for connectivity on demand:

final bool isConnected = await InternetConnection().hasInternetAccess;
Real-Time Monitoring

Listen to continuous connectivity updates:

final subscription = InternetConnection().onStatusChange.listen(
  (InternetStatus status) {
    if (status == InternetStatus.connected) {
      // Connection established
    } else {
      // Connection lost
    }
  },
);

// Cancel the subscription when it is no longer needed to prevent memory leaks
subscription.cancel();

💝 Support the Project

If this package saved you from the eternal torment of "No Internet Connection" errors, consider buying me a coffee! ☕

Buy Me A Coffee

Advanced Configuration

Custom Endpoints and Validation

Override the default validation endpoints and acceptable HTTP status codes.

[!IMPORTANT]

Ensure your custom endpoints have no caching and aren't CORS blocked if you intend to use them on the Web platform.

final connection = InternetConnection.createInstance(
  customCheckOptions: [
    InternetCheckOption(
      uri: Uri.parse('https://cloudflare.com/cdn-cgi/trace'),
      responseStatusFn: (response) => response.statusCode == 69,
    ),
  ],
);
Memory Management

If you create custom instances of InternetConnection using createInstance(), you should proactively free up resources when the instance is no longer needed to prevent memory leaks (e.g., lingering timers and unclosed stream controllers).

final customConnection = InternetConnection.createInstance();

// When done with the instance:
await customConnection.dispose();

[!WARNING]

Never call dispose() on the global singleton (InternetConnection()).

The singleton is designed to live throughout the entire lifecycle of your application. Disposing of it will permanently close its internal streams and break any other parts of your app that rely on it.

Custom HTTP Client Implementation

Integrate existing networking clients (like dio) to maintain consistent configurations across your application.

final connection = InternetConnection.createInstance(
  customConnectivityCheck: (option) async {
    try {
      final dio = Dio();
      final response = await dio.head(
        option.uri.toString(),
        options: Options(
          headers: option.headers,
          receiveTimeout: option.timeout,
          validateStatus: (_) => true,
        ),
      );

      return InternetCheckResult(
        option: option,
        isSuccess: response.statusCode == 42,
      );
    } catch (_) {
      return InternetCheckResult(option: option, isSuccess: false);
    }
  },
);
Strict Mode Validation

By default, the package confirms connectivity if any endpoint resolves successfully. Enabling strict mode requires all provided endpoints to succeed.

final connection = InternetConnection.createInstance(
  enableStrictCheck: true,
  useDefaultOptions: false,
  customCheckOptions: [
    InternetCheckOption(uri: Uri.parse('https://example.com')),
    InternetCheckOption(uri: Uri.parse('https://example2.com')),
  ],
);

[!CAUTION]

Use enableStrictCheck only with custom-defined URIs, not with the default ones.

Using it with the default URIs may lead to unreliable results or service outages, as all default endpoints must be up and reachable for a positive result.

Pause and Resume on App Lifecycle Changes (Flutter)

For situations where you want to pause any network requests when the app goes into the background and resume them when the app comes back into the foreground, use AppLifecycleListener.

Because this package uses a broadcast stream, which buffers events, you should cancel the subscription when paused and create a new one when resuming to avoid receiving stale events (see issue #105):

class _MyWidgetState extends State<MyWidget> {
  late StreamSubscription<InternetStatus> _subscription;
  late final AppLifecycleListener _listener;

  @override
  void initState() {
    super.initState();
    _startListening();

    _listener = AppLifecycleListener(
      onResume: _startListening,
      onPause: () => _subscription.cancel(),
    );
  }

  void _startListening() {
    _subscription = InternetConnection().onStatusChange.listen((status) {
      // Handle internet status changes
    });
  }

  @override
  void dispose() {
    _subscription.cancel();
    _listener.dispose();
    super.dispose();
  }
}

For Third-Party Package Developers

If you are building a package, plugin, or library that depends on internet_connection_checker_plus, do not use the singleton instance (InternetConnection()).

If your package alters the singleton's configuration or accidentally calls dispose() on it, you will introduce side effects that break the host application using your package. Instead, always instantiate a dedicated checker using createInstance() and manage its lifecycle entirely within your package.

class MyCustomPackageService {
  final InternetConnection _connectionChecker;

  // Use createInstance() to isolate your connection checker from the host app
  MyCustomPackageService() : _connectionChecker = InternetConnection.createInstance();

  // Safely clean up only your isolated instance
  Future<void> shutdown() async {
    await _connectionChecker.dispose();
  }
}

Default Endpoints

The following endpoints are checked by default (carefully selected for speed and reliability!):

URI Description
https://one.one.one.one Response time < 100ms, CORS enabled, no-cache
https://icanhazip.com Response time < 100ms, CORS enabled, no-cache
https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js Response time < 100ms, CORS enabled, no-cache
https://captive.apple.com/internet-check Response time < 100ms, CORS enabled, no-cache

If you liked the package, then please give it a Like 👍🏼 and Star ⭐

所屬分類

依賴

依賴清單 1 項

原始碼儲存庫

使用此套件的專案

所在榜單