パッケージ、リポジトリ、アプリカテゴリを検索

パッケージ詳細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 件

ソースリポジトリ

このパッケージを使用しているプロジェクト

ランキング