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

패키지 상세v3.0.0

connecteo

connectivity_plus를 래핑하고 추가적인 데이터 연결 확인 기능을 추가하는 플러그인입니다.

30일 다운로드
1.4천
좋아요
69
Pub 점수
80

패키지 설치

flutter pub add connecteo

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Connecteo는 connectivity_plus를 확장하여 향상된 네트워크 연결 상태 모니터링을 제공하는 Flutter 플러그인입니다. 데이터 연결의 신뢰성을 위한 추가 검사를 제공하여 개발자가 단순히 장치가 온라인인지 여부를 확인할 뿐만 아니라 연결의 품질과 유형도 파악할 수 있도록 도와줍니다. 강력한 네트워크 인식을 위해 설계되었으며 실시간 업데이트를 지원하고 안정적인 연결 감지를 필요로 하는 앱에 원활하게 통합됩니다. 직관적인 API를 통해 네트워크 상태 변경을 간편하게 처리할 수 있으며 일관된 인터넷 접근이 필요한 애플리케이션에 이상적입니다.

사용 사례

  • 실시간 앱 연결 모니터링
  • 오프라인 모드 감지
  • 데이터 사용 최적화
  • 네트워크 품질 평가
  • 연결 기반의 앱 동작 적응
  • 백그라운드 동기화 관리

주요 기능

  • 기본적인 온라인/오프라인 상태를 넘어서는 향상된 연결성 검사
  • 모바일 및 Wi-Fi 데이터 연결 유형 지원
  • 실시간 연결 상태 업데이트
  • 기존 connectivity_plus 워크플로우와의 간단한 통합
  • 경량이며 최소한의 종속성
  • 크로스 플랫폼 호환성

적합한 대상

  • 신뢰할 수 있는 네트워크 상태가 필요한 앱
  • connectivity_plus를 사용하는 개발자들은 이미
  • 오프라인 기능을 갖춘 애플리케이션
  • 실시간 통신 또는 동기화 기능
  • 모바일 앱은 데이터 사용에 민감합니다
  • 네트워크 인식형 UI/UX 디자인

고려 사항

  • Android 및 iOS에서 인터넷 권한이 필요합니다
  • 연결 상태에만 제한됨—데이터 전송 모니터링 없음
  • 실패한 연결에 대한 내장된 재시도 로직 없음
  • 기저 연결성_plus 구현에 의존합니다
  • 약한 신호와 같은 에지 케이스 처리를 위해 추가 조치가 필요할 수 있습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

connecteo

A plugin that wraps connectivity_plus and adds some checks that guarantee connection to the internet.

Contents

Motivation

connectivity_plus is a great package for checking internet status but comes with a single flaw - it checks only the connection type, not the internet connection data. It means that it can not guarantee you connection data, for example, when being under a Wifi access which does not have the internet connection. In such a scenario, the network requests will fail when theoretically they shouldn't due to being online.

A purpose of the plugin was to add some extra checks, on top on existing connectivity_plus's API, that make sure our connection to the internet is reliable when we are online.

Setup

You can install the package from your project's terminal:

flutter pub add connecteo

or add the dependency manually inside your pubspec.yaml:

dependencies:
  connecteo: # desired version

Then you can use connecteo's ConnectionChecker class wherever you want:

import 'package:connecteo/connecteo.dart';

final connecteo = ConnectionChecker();
// Sample checking the internet connection
final hasInternetConnection = await connecteo.isConnected;

How it works

The statement about a reliable internet connection is true when all these conditions are met:

  • A new (or previous) connection type is the online one - it is kind of self-explanatory. The connection type cannot be .none. Every other type is classified as online.
  • (On native platforms) A socket connection has to be opened and successfully established against at least one address - ConnectionChecker defines a default list of IP addresses that are globally available DNS resolvers. When at least one socket connection succeeds with its address, the information about the successful connection is returned, signaling the data connection. On the other hand, when all the socket connection trials fail, the ConnectionChecker informs about a lack of internet connection.
  • (on the Web platform) - situation here is similar to the native platform, but instead of the socket connection, the http call is being made. If we receive a response with 200 status code from one URL at least, the information about a successful connection is returned.
  • (optional) a response from the provided Base Url address has to be successful - if host address for the Base Url was provided in ConnectionChecker constructor, the host lookup is being made against the Base Url. If the lookup process will finish successfully without any SocketException then the condition is being met. This check was dictated by cases where an internet connection got back from an offline state, but the requests to the Base Url were failing for the first few seconds. It was causing some confusion because, in the majority of cases, we expect successful requests once the connection gets back online.

Usage

ConnectionChecker init

There are a couple of parameters (with its default values) that the ConnectionChecker's constructor takes - you can modify them to suit your needs:

  • checkHostReachability - let's you specify if you want to open the socket connections on native platforms (or make an http call on a web platform) against the list of addresses. Its default value is set to true.
  • checkConnectionEntriesNative - a list of custom ConnectionEntry which will be used to open the socket connections. The default list contains three ip addresses: CloudFlare (1.1.1.1), Google (8.8.4.4) and OpenDNS (208.67.222.222). This argument should be used only on native platforms.
  • checkConnectionEntriesWeb - a list of custom ConnectionEntry which will be used to check the responses from urls. At least one of the provided urls here has to return a response with an http status 200. The default list contains the following addresses: https://one.one.one.one/, https://jsonplaceholder.typicode.com/posts/1 and http://worldtimeapi.org/api/timezone. This argument should be used only on Web platforms.
  • hostReachabilityTimeout - let's you specify the Duration which is being used for the timeout for each ConnectionEntry and its socket's opening. The default value is 3 seconds.
  • baseUrlLookupAddress - a String URL which indicates the address you want to lookup during connection checks. Once you provide your URL, the connectionStream and isConnected will return true values only after a successful host lookup. Its default value is null.
  • requestInterval - it is a Duration which is being used for the interval how often the internet connection status should be refreshed. By default, its value is set to 3 seconds.
  • failureAttempts - the number of maximum trials between changing the online to offline state.When the lost connection won't go back after number of failureAttempts, the connectionStream and isConnected will return false values until the connection gets back. The default value is set to 4 attempts.

Example:

final connecteo = ConnectionChecker(
    checkHostReachability: true,
    checkConnectionEntriesNative: [
        ConnectionEntry.fromIpAddress(
            '1.0.0.1', // CloudFlare
        ),
        ConnectionEntry(
            '208.67.220.220', // OpenDNS
            ConnectionEntryType.ip,
        ),
    ],
    checkConnectionEntriesWeb: [
        ConnectionEntry.fromUrl(
            'https://one.one.one.one/', // CloudFlare
        ),
    ],
    hostReachabilityTimeout: Duration(seconds: 5),
    baseUrlLookupAddress: 'https://pub.dev/',
    failureAttempts: 7,
    requestInterval: Duration(seconds: 5),
);
get connectionStream

Returns the reliable internet connection status with the help of Stream<bool>. It yields its value every time when connection type will change or desired interval (ConnectionChecker's constructor argument) will pass.

Example:

final connecteo = ConnectionChecker();

final subscription = connecteo.connectionStream.listen((isConnected) {
    if (isConnected) {
        // Handle the logic when the app is online
    } else {
        // Handle the logic when the app is offline
    }
});
get isConnected

Returns the actual, reliable internet connection status for the present moment. Similar to above, but its return type is Future<bool>.

Example:

final connecteo = ConnectionChecker();

final hasInternetConnection = await connecteo.isConnected;
if (hasInternetConnection) {
    // Handle the one-time check when the app is online
}
get connectionTypes

Returns the current connection type.

Example:

final connecteo = ConnectionChecker();

final types = await connecteo.connectionTypes;
if (types.contains(ConnectionType.mobile)) {
    // Handle the logic when the application uses cellular data
}
untilConnects()

A method which resolves as soon as internet connection status get back from offline state. Handy when you want to trigger some kind of action once, after internet data connection get back but you do not want to use the connectionStream.

Example:

final connecteo = ConnectionChecker();

connecteo.untilConnects().then((_) {
    // Handle the logic when the internet connection data get back
});
Custom network checker

In the ConnectionChecker there's a factory method fromReachabilityChecker designed for integrating custom network checker implementations. To begin, you'll need to create a class that extends HostReachabilityChecker and implements 2 methods hostLookup and canReachAnyHost.

Note If you don't want to use one of those canReachAnyHost or hostLookup methods, simply return true`.

Let's look at parameters of fromReachabilityChecker constructor:

  • hostReachabilityChecker - it is a custom implementation of network checker.
  • requestInterval - it is a Duration which is being used for the interval how often the internet connection status should be refreshed. By default, its value is set to 3 seconds.
  • failureAttempts - the number of maximum trials between changing the online to offline state.When the lost connection won't go back after number of failureAttempts, the connectionStream and isConnected will return false values until the connection gets back. The default value is set to 4 attempts.

Example:


class CustomReachabilityChecker extends HostReachabilityChecker {
// TODO implementation 
}

final connecteo =  ConnectionChecker.fromReachabilityChecker(
  hostReachabilityChecker: CustomReachabilityChecker(),
  failureAttempts: 7,
  requestInterval: Duration(seconds: 5),
);

For more detailed information about the package possibilities, visit the API documentation.

카테고리

의존성

의존성 목록 3 개

소스 저장소

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

아직 데이터가 없습니다.