Skip to content

shahanajparvin/flutter-dio-cache-interceptor_example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Flutter Dio Cache Interceptor Example

Overview

Caching is a crucial process for storing API responses on a user's device to reduce network requests and improve performance in Flutter apps. This example demonstrates how to implement caching for API requests using the Dio HTTP client and the Dio Cache Interceptor.

Key Components

  • Dio: A powerful HTTP client for Flutter.
  • Dio Cache Interceptor: An interceptor for Dio that allows efficient API response caching.
  • Hive: A fast and lightweight key-value database in Dart used as the cache store.

Implementation Steps

1. Add Dependencies

In your `pubspec.yaml` file, add the required packages:


dependencies:
  dio: ^4.0.6
  dio_cache_interceptor: ^3.3.0
  dio_cache_interceptor_hive_store: ^3.2.0
  hive: ^2.0.5

2. Set Up Cache Directory

Get the temporary directory on the device where cached data will be stored. It's recommended to use the temporary directory provided by Flutter:


var cacheDir = await getTemporaryDirectory();

3. Build Cache Store

Create a cacheStore object, specifying the cache directory path and a unique hiveBoxName for your app:


var cacheStore = HiveCacheStore(
  cacheDir.path,
  hiveBoxName: "your_app_name",
);

4. Define Cache Options

Customize cache options to control caching behavior, such as cache policy, priority, maxStale duration, key building, and more:


var customCacheOptions = CacheOptions(
  store: cacheStore,
  policy: CachePolicy.forceCache,
  priority: CachePriority.high,
  maxStale: const Duration(minutes: 5),
  hitCacheOnErrorExcept: [401, 404],
  keyBuilder: (request) {
    return request.uri.toString();
  },
  allowPostMethod: false,
);

5. Build Dio with Cache Interceptor

Create a Dio instance and add the cache interceptor with your custom cache options:


var customDio = Dio()
  ..interceptors.add(DioCacheInterceptor(options: customCacheOptions));

Best Practices for Network Calling and Error Handling

Follow these best practices when using Dio for network requests:

  • Use Dio's try-catch mechanism to handle network errors gracefully.
  • Implement loading indicators to provide feedback during network requests.
  • Handle timeouts and connectivity issues.
  • Display appropriate error messages to the user.

Usage

Now, all your GET requests made using the customDio object will be cached in the user's device storage temporary directory while following best practices for network calling and error handling.

Feel free to explore and customize this example for your Flutter app's caching needs.