Skip to content

A Flutter package for seamless internet connection management. Automatically detect connectivity changes, handle outages with customizable widgets, and execute logic when the connection is restored—all with minimal code.

License

Notifications You must be signed in to change notification settings

MAlazhariy/internet_state_manager

Repository files navigation

Stand With Palestine

Internet State Manager 🌐

pub package License: BSD 3-Clause

A powerful Flutter package for seamless internet connection management. Not just another connectivity checker — it's a complete solution that handles, monitors, and manages internet states across your entire app with minimal code! 🚀

⚡ Key Features

  • 🧩 Minimal Code — Wrap once, works everywhere — no boilerplate
  • ⏱️ Save Time — Eliminate repetitive connectivity checks on every screen
  • 🎯 Better UX — Auto-handle offline states with smooth built-in UI transitions
  • 🔄 Smart Auto-Refresh — Fetch fresh data automatically when connection restores via onConnectionRestored
  • 🎯 Accurate Detection — Goes beyond Wi-Fi checks — verifies actual internet access
  • 📡 Real-time Monitoring — Stream-based connectivity updates with customizable check intervals
  • 🎨 Fully Customizable — Use built-in widgets or create your own custom offline screens

💡 How It Works

Simple 3-step setup:

  1. Initialize → Wrap your app with InternetStateManagerInitializer
  2. Wrap → Add InternetStateManager to any screen
  3. Done! → The package handles everything automatically ✨

Behind the scenes:

  • 🔍 Periodically checks actual internet access (not just Wi-Fi)
  • 🖼️ Shows a built-in "No Internet" screen when disconnected
  • 🔄 Automatically restores your screen when connection returns
  • 📞 Optionally triggers callbacks to refresh your data

📱 Demo

Internet State Manager Demo

The demo shows:

  • First Screen: Uses InternetStateManager with a bottom widget bar that appears when disconnected, showing "لا يوجد اتصال بالانترنت" (No internet connection) with a "Try again" button
  • Second Screen: Uses InternetStateManager with NoInternetScreen - automatically appears when WiFi is disconnected
  • Auto-detection: Both screens automatically check internet connection periodically based on library options
  • Connection Restored: When WiFi reconnects, "Internet connection restored" message appears and content is restored

📋 Requirements

  • Flutter: ≥ 3.19.0
  • Dart: ≥ 3.3.0 <4.0.0
  • iOS: ≥ 12.0
  • macOS: ≥ 10.14
  • Java: 17
  • Android Gradle Plugin: ≥ 8.12.1
  • Gradle Wrapper: ≥ 8.13

🚀 Getting Started

Installation

Add to your pubspec.yaml:

dependencies:
  internet_state_manager: ^1.10.0

Then run:

flutter pub get
Platform Configuration

Android

Add these permissions to android/app/src/main/AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    
    <!-- Required for internet_state_manager -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    
    <application ...>

iOS

Add to ios/Runner/Info.plist:

<key>NSLocalNetworkUsageDescription</key>
<string>This app requires access to the local network to monitor connectivity status.</string>

📖 Usage

1. Initialize the Package

Wrap your app with InternetStateManagerInitializer:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // ⚠️ REQUIRED: Initialize before runApp
  await InternetStateManagerInitializer.initialize();

  runApp(
    InternetStateManagerInitializer(
      options: InternetStateOptions(
        checkConnectionPeriodic: const Duration(seconds: 3),
        showLogs: true,
      ),
      child: const MyApp(),
    ),
  );
}
2. Wrap Your Screens

Simply wrap any screen with InternetStateManager:

@override
Widget build(BuildContext context) {
  return InternetStateManager(
    child: Scaffold(
      body: Center(
        child: Text('Your content here'),
      ),
    ),
  );
}

🎨 Customization

Builder Widget

Full control over your UI based on connection state:

InternetStateManager.builder(
  builder: (context, state) {
    return Scaffold(
      body: Center(
        child: state.status.isConnected
            ? Text('✅ Connected!')
            : Text('❌ No internet'),
      ),
    );
  },
);
Connection Restoration Callback

Execute logic when connection is restored:

InternetStateManager(
  onRestoreInternetConnection: () {
    // Refresh data, sync, etc.
    setState(() {
      fetchData();
    });
  },
  child: MyScreen(),
);
Custom No-Internet Screen

Replace the default disconnected UI:

InternetStateManager(
  noInternetScreen: CustomNoInternetWidget(),
  child: MyScreen(),
);
Options Configuration
InternetStateOptions(
  // Check interval when connected
  checkConnectionPeriodic: const Duration(seconds: 12),
  
  // Check interval when disconnected (faster retry)
  disconnectionCheckPeriodic: const Duration(seconds: 3),
  
  // Custom colors
  errorBackgroundColor: Colors.red,
  onBackgroundColor: Colors.white,
  
  // Custom labels
  labels: InternetStateLabels(
    noInternetTitle: () => 'Oops! No Connection',
    descriptionText: () => 'Please check your network',
    tryAgainText: () => 'Retry',
  ),
  
  // Debug logs
  showLogs: true,
)

🛠️ Advanced Usage

Dio Interceptor (Optional)

If you use Dio, you can optionally add the interceptor to keep connectivity state fresh with each HTTP request:

final dio = Dio();
dio.interceptors.add(InternetStateManagerInterceptor());

The interceptor triggers a non-blocking connectivity check on every request, keeping the UI state updated without slowing down your API calls.

Note: This is completely optional. The package works perfectly without it.

Context Extensions

Access connection state from anywhere:

// Check current state
bool isConnected = context.internetState.isConnected;

// Manual connection check
await context.internetCheck();

// Listen to connection stream
context.internetStateStream.listen((state) {
  print('Connection changed: ${state.isConnected}');
});
Global App Integration

Apply to your entire app:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      builder: (context, child) => InternetStateManager(child: child!),
      home: HomeScreen(),
    );
  }
}

🙏 Credits

Developed by Mostafa Alazhariy

Dependencies:


👥 Contributors

contributors


⭐ Support

If you find this package helpful, please give it a star on GitHub!

Feel free to open issues or submit PRs.

About

A Flutter package for seamless internet connection management. Automatically detect connectivity changes, handle outages with customizable widgets, and execute logic when the connection is restored—all with minimal code.

Topics

Resources

License

Stars

Watchers

Forks