패키지, 저장소 및 앱 카테고리 검색

패키지 상세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 업데이트
  • 백그라운드 연결 풀링

주요 기능

  • 서브초 응답 시간
  • 크로스 플랫폼 호환성
  • 순수한 다트 구현
  • 간단하고 직관적인 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 개

소스 저장소

이 패키지를 사용하는 프로젝트

순위