flutter_offline

repository·master·Indexed 23 days ago

https://github.com/jogboms/flutter_offline

A utility for Flutter applications to handle online and offline connectivity states across iOS, Android, Web, macOS, Linux, and Windows. It provides the OfflineBuilder widget for reacting to connectivity changes and the OfflineRetryController for managing manual retries with exponential backoff and configurable cooldowns.

Tokens
1.9K
Snippets
4
Records
8
Agent score
30%

What's inside flutter_offline

  1. Implement manual retry with OfflineRetryController

    master

    The OfflineRetryController allows you to manage manual connectivity retries with exponential backoff.

    Key features:

    • Exponential backoff: Automatically increases delay (1s, 2s, 4s, 8s, 16s).
    • Configurable: Set maxRetries and retryCooldown.
    • Reactive: Extends ChangeNotifier, so you can add a listener to trigger setState() when retry status changes.
    • Auto-reset: Resets automatically upon reconnection.

    To use it, instantiate the controller, add a listener, and pass it to the retryController property of an OfflineBuilder.

    class _MyWidgetState extends State<MyWidget> {
      late final OfflineRetryController _retryController;
    
      @override
      void initState() {
        super.initState();
        _retryController = OfflineRetryController(
          maxRetries: 5,
          retryCooldown: const Duration(seconds: 2),
        );
        // Listen to changes to update UI (e.g., retry count or status)
        _retryController.addListener(() => setState(() {}));
      }
    
      @override
      void dispose() {
        _retryController.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return OfflineBuilder(
          retryController: _retryController,
          connectivityBuilder: (context, connectivity, child) {
            final connected = !connectivity.contains(ConnectivityResult.none);
            return Column(
              children: [
                Text(connected ? 'ONLINE' : 'OFFLINE'),
                if (!connected)
                  ElevatedButton(
                    // Use .canRetry to check if more attempts are allowed
                    onPressed: _retryController.canRetry ? _retryController.retry : null,
                    child: Text('Retry (${_retryController.retryCount}/5)'),
                  ),
              ],
            );
          },
        );
      }
    }
  2. How OfflineBuilder and OfflineRetryController work together

    master

    When using both components, OfflineBuilder automatically manages the lifecycle of the OfflineRetryController.

    When OfflineBuilder detects that the device has reconnected (i.e., the connectivity list no longer contains ConnectivityResult.none), it automatically calls retryController.reset(). This resets the retryCount to 0 and clears the lastRetryTime, allowing the user to start a fresh retry cycle if they lose connection again.

    This ensures that your retry state is always synchronized with the actual network availability reported by the device.

  3. Use the OfflineBuilder widget

    master
    The OfflineBuilder widget is the primary way to react to connectivity changes in your UI. It uses a connectivityBuilder callback that provides the current list of ConnectivityResult values. You can use these results to determine if the device is online (e.g., by checking if the list does not contain ConnectivityResult.none).
  4. Customize retry behavior with CustomRetryController

    master

    You can extend OfflineRetryController to inject custom logic during the retry lifecycle by overriding onRetry() or onRetryError().

    class CustomRetryController extends OfflineRetryController {
      CustomRetryController() : super(maxRetries: 3);
    
      @override
      Future<void> onRetry() async {
        print('Retrying connection...');
      }
    
      @override
      void onRetryError(Object error, StackTrace stackTrace) {
        print('Retry failed: $error');
      }
    }
  5. Manage retry logic with OfflineRetryController

    master

    The OfflineRetryController is a ChangeNotifier used to manage manual retry attempts when a connection is lost. It implements exponential backoff and provides state information that can be used to drive UI elements like retry buttons.

    Key Features

    • Exponential Backoff: Automatically increases the delay between retries using the formula 2^retryCount seconds.
    • Retry Throttling: Uses retryCooldown to prevent users from spamming the retry action.
    • State Tracking: Provides retryCount, isRetrying, and canRetry to help you build responsive UI.

    Customizing Retry Behavior

    To perform actual network requests or specific logic during a retry, you must subclass OfflineRetryController and override onRetry() and onRetryError().

    Implementation Example

    class MyRetryController extends OfflineRetryController {
      MyRetryController({
        int maxRetries = 5,
        Duration retryCooldown = const Duration(seconds: 2),
      }) : super(maxRetries: maxRetries, retryCooldown: retryCooldown);
    
      @override
      Future<void> onRetry() async {
        // Implement your actual network call or data sync here
        await myApiService.fetchData();
      }
    
      @override
      void onRetryError(Object error, StackTrace stackTrace) {
        print('Retry failed: $error');
      }
    }
  6. Use the OfflineBuilder widget to manage connectivity UI

    master

    The OfflineBuilder widget is the primary entry point for reacting to connectivity changes in your Flutter application. It listens to connectivity updates and provides the current list of ConnectivityResult values to a connectivityBuilder function.

    To use it, you must provide either a builder or a child. The connectivityBuilder receives the current connectivity state and allows you to decide how to render your UI based on whether the device is online or offline.

    Key parameters:

    • connectivityBuilder: A function (context, connectivity, child) => Widget that receives the current list of ConnectivityResult.
    • debounceDuration: The time to wait before emitting a connectivity change (defaults to 3 seconds) to avoid UI flickering during unstable network transitions.
    • retryController: An optional OfflineRetryController to manage manual retry logic.
    • errorBuilder: An optional widget to display if a platform error occurs during connectivity monitoring.