flutter_network_guard library
flutter_network_guard
A complete network reliability toolkit for Flutter: connectivity detection, real Internet reachability, server health, network quality, retry with backoff, request protection (deduplication, cancellation, stale-response safety), offline queue with optional persistence, offline cache, and network-aware UI — all state-management agnostic (Provider, Riverpod, BLoC, GetX, Cubit, ValueNotifier, setState) and opt-in feature by feature.
Quick start:
await NetworkGuard.initialize();
if (NetworkGuard.instance.isOnline) { /* ... */ }
See the package README for the full guide, including retry, offline queueing, caching and the Dio/http adapters.
Classes
-
CacheEntry<
T> - A single cached value with its expiration metadata.
- CacheManager
- A small, opt-in, in-memory cache with TTL and size limits, plus helpers for the common cache/network interaction patterns (CachePolicy).
- CancelToken
-
A cooperative cancellation token for calls made through
NetworkGuard.execute. - ConnectivityAdapter
-
Translates
connectivity_plusresults into this package's ConnectivityType, so the public API never leaks a third-party type. Swap this out viaConnectivityAdapter.customif you need a different underlying connectivity source. - ConnectivityService
- Watches the device's local network connectivity type.
- InMemoryQueueStorage
- An in-memory QueueStorage that does not persist across restarts. Useful for tests, or apps that explicitly want a session-only queue.
- InternetChecker
- Performs real Internet reachability checks against one or more HTTP(S) endpoints.
- InternetCheckResult
- The outcome of a single Internet reachability attempt.
- LatencyMonitor
- Turns a raw latency sample into a NetworkQuality using configurable NetworkQualityThresholds, and keeps a short rolling history for callers that want a smoothed/average view instead of a single noisy sample.
- MetricsSnapshot
- A point-in-time snapshot of NetworkMetrics counters.
- NetworkAware
- Swaps between child and offlineBuilder depending on network status. Use this to show a dedicated offline page/state instead of the normal screen.
-
NetworkCancelled<
T> - The operation was cancelled before it completed — either explicitly, or because a deduplication policy replaced/cancelled it.
- NetworkDebugPanel
- A developer-only panel showing live network state, useful while integrating this package. Disabled in release builds unless forceEnabled is set — it's meant for development, not end users.
- NetworkEvent
- A single entry in the network event/history log — useful for debugging ("what happened to my connection at 12:06?").
-
NetworkFailure<
T> - The operation failed after exhausting retries (or immediately, if no retry policy allowed another attempt).
- NetworkGuard
- The main entry point for flutter_network_guard.
- NetworkGuardBuilder
- Rebuilds builder every time NetworkGuard's network state changes. The lowest-level, most flexible network-aware widget — NetworkAware and NetworkStatusBanner are built on top of this.
- NetworkGuardButton
- A tap target that guards against duplicate taps and offline submissions.
- NetworkGuardConfig
- Central configuration for NetworkGuard.
- NetworkInfo
- An immutable snapshot of everything this package knows about the network at checkedAt.
- NetworkLogger
- Internal logger used throughout the package.
- NetworkMetrics
-
Tracks simple counters across calls made through
NetworkGuard. -
NetworkOffline<
T> - The operation was not attempted because the device is offline (and no offline queueing was configured for this call).
- NetworkQualityThresholds
- Configurable latency boundaries used to classify a latency sample into a NetworkQuality value.
-
NetworkQueued<
T> -
The operation was queued for later delivery because the device was
offline and offline queueing was configured for this call. See the
queuemodule. -
NetworkRequest<
T> -
A description of a single call made through
NetworkGuard.execute. -
NetworkResult<
T> -
The outcome of a call made through
NetworkGuard.execute. - NetworkService
- The internal engine that combines connectivity, Internet reachability, server health and network quality into a single NetworkInfo stream, applying debouncing, periodic re-checks, app lifecycle awareness and recovery callbacks.
- NetworkStatusBanner
- A banner that appears when the network goes offline and briefly shows a "back online" state when it's restored, then disappears.
-
NetworkSuccess<
T> - The operation completed successfully.
-
NetworkTimeout<
T> - The operation exceeded its configured timeout.
- OfflineBanner
- A minimal alias of NetworkStatusBanner with defaults suited to a plain "offline only" indicator (no "back online" flash).
- OfflineQueue
- A priority-ordered, optionally-persistent queue of writes deferred while offline and replayed once Internet is available.
- QueuedRequest
- A serializable description of a deferred write, queued while the device is offline and replayed once Internet returns.
- QueueStorage
- Persists QueuedRequests so they survive app restarts.
- RequestDeduplicator
- Prevents accidental duplicate calls to the same logical operation — e.g. a user double-tapping "Submit" before the first tap's request has returned.
- RequestManager
- Protects against the "stale response" problem: several calls to the same logical operation are in flight (e.g. search-as-you-type firing on every keystroke), and a slower earlier response arrives after a faster later one, overwriting fresher data with older data.
- RetryEngine
-
Runs an async
operation, retrying according to RetryPolicy until it succeeds, exhausts its attempts, or fails with an error the policy decides is not retryable. - RetryPolicy
- Configures how RetryEngine retries a failed operation.
- ServerHealth
- A snapshot of a single server's health, as of the last check.
- ServerHealthChecker
- Performs a single health check for a ServerHealthConfig.
- ServerHealthConfig
- Configuration for checking a single server/API's health.
- ServerHealthMonitor
- Periodically checks one or more ServerHealthConfigs and exposes their latest ServerHealth snapshots, each server tracked independently (an auth server going down doesn't affect what this reports for your payments API).
-
A QueueStorage backed by
shared_preferences, storing the whole queue as one JSON-encoded list under storageKey.
Enums
- CachePolicy
- How a cached value interacts with a live fetch.
- ConnectivityType
- The physical/link-layer connection type reported by the platform.
- DeduplicationPolicy
- How RequestDeduplicator should handle a call whose key matches one already in flight.
- HttpMethod
- HTTP method for a QueuedRequest. Kept as a small enum (rather than a raw string) so serialized queue entries stay well-formed.
- LogLevel
- Controls how much NetworkLogger output the package produces.
- NetworkEventType
- The kind of transition a NetworkEvent represents.
- NetworkQuality
- A coarse, latency-based estimate of connection quality.
- NetworkStatus
- The high-level, user-facing network status.
- QueuePriority
- Priority used to order pending tasks within OfflineQueue.
- QueueTaskStatus
- The current lifecycle state of a QueuedRequest inside OfflineQueue.
- RetryStrategy
- How delay grows between retry attempts.
Typedefs
- LogSink = void Function(LogLevel level, String message)
-
Signature for a custom log sink. Defaults to printing via
printthroughNetworkLogger.debugPrintif none is supplied. - NetworkBannerBuilder = Widget Function(BuildContext context, NetworkInfo info, bool isBackOnline)
- Signature for a custom banner builder, given the current NetworkInfo and whether it's currently showing a transient "back online" state.
- NetworkButtonBuilder = Widget Function(BuildContext context, VoidCallback? onPressed, bool isLoading)
- Signature for building the button's visual, given whether a request triggered by this button is currently in flight.
- NetworkCallback = void Function()
- Signature for a no-argument network lifecycle callback.
- NetworkInfoCallback = void Function(NetworkInfo info)
- Signature for network lifecycle callbacks that receive the triggering NetworkInfo snapshot.
-
QueuedRequestExecutor
= Future<
bool> Function(QueuedRequest task) - Signature for the function that actually performs a queued task's underlying HTTP call.
Exceptions / Errors
- CacheException
- Thrown for cache-related failures (e.g. persistence errors, corrupt entries that could not be deserialized).
- Thrown when a local connection exists but Internet is not reachable.
- NetworkGuardException
- Base class for every exception thrown by flutter_network_guard.
- Thrown when there is no local network connection at all.
- QueueException
- Thrown for offline-queue related failures (e.g. persistence errors, queue full, task not found).
- RequestCancelledException
- Thrown when a request was explicitly cancelled, either by the caller or by a deduplication/replacement policy.
- RequestTimeoutException
- Thrown when a request or check exceeds its configured timeout.
- RetryExhaustedException
- Thrown when a retryable request exhausts its configured retry attempts without succeeding.
- Thrown when Internet is reachable but the configured server is not.