Interceptor in Flutter Application

 How to integrate Interceptor in Flutter Application.




What is an interceptor?


  • An interceptor is a middleware component that intercepts and modifies HTTP requests and responses. Interceptors are commonly used to implement features such as authentication, caching, and logging.


How to integrate an interceptor in flutter application?


  • Steps for implementing an interceptor in flutter application.


  • Flutter has a built-in Interceptor class from the dio package, which is a popular HTTP client for Flutter. With Interceptor, you can intercept and modify HTTP requests and responses before they are sent or received.


  1. Add dio package in your existing or new flutter project.

→ flutter pub add dio


  1. Create a custom Dio file. In this file add your interceptor code.

→ custom_dio.dart

import 'package:dio/dio.dart';

import 'dart:developer' as dev;

class CustomDio {
static final CustomDio _singleton = CustomDio._internal();
var dio = Dio();

factory CustomDio() {
return _singleton;
}

Future<Dio> getDio() async {
dio.interceptors.clear();
dio.interceptors.add(getInterceptorsWrapper());
return dio;
}

InterceptorsWrapper getInterceptorsWrapper() {
return InterceptorsWrapper(onRequest: (
RequestOptions requestOptions,
RequestInterceptorHandler handler,
) {
dev.log('----------------------------> Request Log
<---------------------------------');
dev.log("Headers--> \n ${requestOptions.headers}");
dev.log(
" Type--> ${requestOptions.method} Request-->${requestOptions.uri} \n ");
dev.log(
" extra--> ${requestOptions.extra} data-->${requestOptions.data}
queryParameters-->${requestOptions.queryParameters} \n ");
dev.log('-----------------------------------------
-------------------------------------');
return handler.next(requestOptions);
}, onResponse: (
Response response,
ResponseInterceptorHandler handler,
) {
dev.log('----------------------------> Response Log
<---------------------------------');
dev.log("data--> ${response.data}");
dev.log(
"Response-->${response.realUri} \n statusCode--> ${response.statusCode}
\n path--> ${response.requestOptions.path}
\n Headers--> \n ${response.headers} ");
dev.log('-------------------------------------------
-----------------------------------');
return handler.next(response);
}, onError: (DioError dioError, ErrorInterceptorHandler handler) {
dev.log('----------------------------> Error Log
<---------------------------------');
dev.log("error -->${dioError.error} message -->${dioError.message}");
dev.log(
"Type--> ${dioError.requestOptions.method} url-->${dioError.requestOptions.uri}
\n Headers--> \n
${dioError.requestOptions.headers} data--> ${dioError.requestOptions.path}");
handler.next(dioError);
dev.log('---------------------------------------------------------------------
---------');
});
}

CustomDio._internal();
}





  1. After this call custom Dio at the time of api call.

                                → product_repository.dart
                              

class ProductRepository {

static var customDio = CustomDio();
static var client;

Future fetchProducts() async{
try {
client = await customDio.getDio();
var response = await client.get('https://dummyjson.com/products/1');
} catch (error, stacktrace) {
if (kDebugMode) {
print("Exception occurred: $error stackTrace: $stacktrace");
}
return [];
}
}

}
  1. Boom..!!!  An interceptor is called so you can see all the details in your log terminal.

                                → Output
                


Comments

Popular posts from this blog

Url Launcher using Flutter

If and Else in Flutter

Flutter Project Migration