Handling Intermittent Network Connectivity in Flutter

Handling Intermittent Network Connectivity in Flutter

Handling Intermittent Network Connectivity in Flutter

Introduction

In Flutter apps that rely on REST APIs, intermittent network connectivity can degrade the user experience. By using caching and retry mechanisms, we can ensure the app remains responsive and functional, even in unstable network conditions. Here's how to implement these strategies effectively.

Strategies to Handle Connectivity Issues

1. Detecting Network Connectivity

Use the connectivity_plus package to monitor network status and adapt app behavior accordingly:

import 'package:connectivity_plus/connectivity_plus.dart';

void checkNetworkStatus() {
  Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
    if (result == ConnectivityResult.none) {
      print('No internet connection');
    } else {
      print('Connected to the internet');
    }
  });
}

        

2. Implementing Caching

Store fetched data locally to ensure the app functions offline. You can use packages like Hive or SQLite for efficient data storage:

import 'package:hive/hive.dart';

void saveData(String key, dynamic data) async {
  var box = await Hive.openBox('cacheBox');
  await box.put(key, data);
}

dynamic getCachedData(String key) async {
  var box = await Hive.openBox('cacheBox');
  return box.get(key);
}

        

3. Implementing Retry Mechanisms

Retry failed requests with an exponential backoff strategy to improve reliability:

Future<void> fetchDataWithRetry(Function fetchFunction, int retryCount) async {
  int attempt = 0;
  while (attempt < retryCount) {
    try {
      await fetchFunction();
      break;
    } catch (e) {
      attempt++;
      await Future.delayed(Duration(seconds: attempt * 2));
    }
  }
}

        

4. Offline-First Approach

Prioritize cached data while fetching updates in the background:

Future<void> fetchData() async {
  final cachedData = await getCachedData('dataKey');
  if (cachedData != null) {
    print('Displaying cached data');
    // Use cached data
  }

  try {
    // Fetch fresh data from the API
    final freshData = await fetchFromApi();
    saveData('dataKey', freshData); // Update cache
  } catch (e) {
    print('Failed to fetch fresh data: $e');
  }
}

        

5. Provide User Feedback

Inform users about connection status and fallback behavior using UI elements like SnackBars:

ScaffoldMessenger.of(context).showSnackBar(
  SnackBar(content: Text('You are offline. Displaying cached data.')),
);

        

Complete Example

Future<void> fetchDataWithNetworkHandling() async {
  try {
    final result = await fetchFromApi();
    print('Fetched data: $result');
    saveData('dataKey', result); // Save fresh data
  } on SocketException {
    print('No internet connection. Loading cached data...');
    final cachedData = await getCachedData('dataKey');
    if (cachedData != null) {
      print('Using cached data: $cachedData');
    } else {
      print('No cached data available.');
    }
  } catch (e) {
    print('Unexpected error: $e');
  }
}

        

© 2024 Flutter Tutorials Blog. All rights reserved.

Comments

Popular Posts