Flutter Network Toolkit

pub package License: MIT Flutter

A comprehensive, production-grade Flutter toolkit for real-time network connectivity monitoring, resilient HTTP networking with automatic exponential backoff retries, ping/latency diagnostics, and customizable offline UI widgets.


Features

  • 🌐 True Internet Reachability: Differentiates between being connected to a local router and having actual WAN internet access (avoids false-positives with captive portals).
  • πŸ”„ Resilient HTTP Client: Wrapper with automatic retries, exponential backoff, randomized jitter, and custom timeout handling.
  • ⚑ Ping & Latency Diagnostics: Measure round-trip time, calculate jitter, and infer connection quality (excellent, good, fair, poor).
  • πŸ›‘οΈ Network Lifecycle Interceptors: Built-in formatted logger (NetworkLoggingInterceptor) and dynamic token authorization (AuthTokenInterceptor).
  • 🎨 Pre-built UI Components:
    • NetworkStatusBuilder: Reactive widget listening to live network transitions.
    • OfflineBanner: Animated top/bottom banner notifying users when offline or back online.
    • NoInternetScreen: Customizable full-screen offline illustration with retry button.
    • ConnectivityAware: Wrap buttons/actions to block execution when offline.
  • πŸ“± Multi-Platform Support: Android, iOS, Web, macOS, Windows, and Linux.

Platform Support

Platform Supported Reachability Mechanism
Android βœ… Socket/DNS + HTTP probe fallback
iOS βœ… Socket/DNS + HTTP probe fallback
Web βœ… Lightweight HTTP 204 HEAD/GET probe
macOS βœ… Socket/DNS + HTTP probe fallback
Windows βœ… Socket/DNS + HTTP probe fallback
Linux βœ… Socket/DNS + HTTP probe fallback

Getting Started

Add flutter_network_toolkit to your pubspec.yaml:

dependencies:
  flutter_network_toolkit: ^1.0.0

Then fetch the package:

flutter pub get

Usage Guide

1. Real-time Connectivity Monitoring

import 'package:flutter_network_toolkit/flutter_network_toolkit.dart';

// Check connectivity on demand
final isConnected = await NetworkWatcher.instance.isConnected;
final info = await NetworkWatcher.instance.checkNetwork();

print('Connected: ${info.isConnected}');
print('Types: ${info.connectionTypes}'); // [ConnectionType.wifi]
print('Quality: ${info.quality}');       // NetworkQuality.excellent

// Listen to stream of network changes
NetworkWatcher.instance.onNetworkInfoChanged.listen((info) {
  if (info.isOffline) {
    print('Device went offline!');
  } else {
    print('Device reconnected with ${info.latencyMs}ms latency');
  }
});

2. Reactive UI with NetworkStatusBuilder

NetworkStatusBuilder(
  connectedBuilder: (context, info) {
    return Text('Online (${info.connectionTypes.first.name})');
  },
  disconnectedBuilder: (context, info) {
    return const Text('You are offline', style: TextStyle(color: Colors.red));
  },
)

3. Animated OfflineBanner

Wrap your screen or Scaffold to show an animated banner when offline:

OfflineBanner(
  position: BannerPosition.top,
  offlineText: 'No internet connection',
  onlineText: 'Back online',
  child: Scaffold(
    appBar: AppBar(title: const Text('My App')),
    body: const Center(child: Text('Main Content')),
  ),
)

4. Resilient HTTP Client with Automatic Retry

final client = NetworkClient(
  baseUrl: Uri.parse('https://api.example.com'),
  defaultTimeout: const Duration(seconds: 10),
  retryPolicy: const RetryPolicy(
    maxRetries: 3,
    initialDelay: Duration(milliseconds: 500),
    backoffMultiplier: 2.0,
    useJitter: true,
  ),
  interceptors: [
    NetworkLoggingInterceptor(logHeaders: true, logBody: true),
    AuthTokenInterceptor(tokenProvider: () async => 'my_jwt_token'),
  ],
);

// Send GET request
try {
  final response = await client.get('/users/profile');
  print('Response (${response.statusCode}): ${response.data}');
} on NoInternetException catch (e) {
  print('User is offline: $e');
} on NetworkTimeoutException catch (e) {
  print('Request timed out: $e');
} on NetworkHttpException catch (e) {
  print('Server returned error ${e.statusCode}: ${e.responseBody}');
}

5. Latency & Network Diagnostics

final diagnostics = NetworkDiagnostics();

// Single ping test
final latency = await diagnostics.measureLatency();
print('Current ping: $latency ms');

// Comprehensive diagnostic report
final report = await diagnostics.runDiagnosticReport();
print('Average Latency: ${report.averageLatencyMs} ms');
print('Jitter: ${report.jitterMs} ms');
print('Packet Loss: ${report.packetLossRate * 100}%');
print('Inferred Quality: ${report.quality}');

6. Guard Interactive Elements with ConnectivityAware

Prevent users from triggering API-heavy actions while disconnected:

ConnectivityAware(
  onTap: () {
    // This callback only runs if device is online
    submitForm();
  },
  onOfflineTap: () {
    // Optional fallback when tapped while offline
  },
  child: ElevatedButton(
    onPressed: null, // Handled automatically by ConnectivityAware
    child: const Text('Submit Order'),
  ),
)

7. Full-Screen NoInternetScreen Fallback

NoInternetScreen(
  title: 'Connection Lost',
  message: 'Please check your Wi-Fi or cellular network settings.',
  retryButtonText: 'Try Again',
  onRetry: () async {
    // Custom reload or verify logic
    await NetworkWatcher.instance.checkNetwork();
  },
)

Example App

Check out the example/ directory for a complete, runnable Flutter demonstration showcasing status badges, ping tests, retry simulation, and offline widgets.

To run the example:

cd example
flutter run

Running Tests

Execute the automated test suite:

flutter test

License

This project is licensed under the MIT License - see the LICENSE file for details.

flutter_network_toolkit

Libraries

flutter_network_toolkit
A comprehensive Flutter toolkit for real-time network connectivity monitoring, reliable HTTP client with automatic retry, ping diagnostics, and ready-to-use offline UI widgets.