Skip to content

Instantly share code, notes, and snippets.

@bellrd
Created September 8, 2021 16:26
Show Gist options
  • Save bellrd/34139ef04cae69e1c5d90fdccf799518 to your computer and use it in GitHub Desktop.
Save bellrd/34139ef04cae69e1c5d90fdccf799518 to your computer and use it in GitHub Desktop.
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:path_provider/path_provider.dart';
import 'constant.dart';
// interceptor for dio
class _LogInterceptor extends Interceptor {
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
print("NET_LOG_REQUEST: ${options.headers}");
print("NET_LOG_REQUEST: ${options.uri}");
print("NET_LOG_REQUEST: ${options.data.toString()}");
return super.onRequest(options, handler);
}
@override
void onError(DioError err, ErrorInterceptorHandler handler) {
print("NET_LOG_ERROR: ${err.response.toString()}");
super.onError(err, handler);
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
print("NET_LOG_HEADERS: ${response.headers}");
print("NET_LOG_RESPONSE: ${response.data}");
super.onResponse(response, handler);
}
}
// singleton
class _MyCookieStorage extends FileStorage {
static final _MyCookieStorage _myCookieStorage = _MyCookieStorage._internal();
factory _MyCookieStorage() {
return _myCookieStorage;
}
String? dir;
@override
Future<void> init(bool persistSession, bool ignoreExpires) async {
var applicationDocumentDir = await getApplicationDocumentsDirectory();
var cookieDir = applicationDocumentDir.path + "/.cookie";
this.dir = cookieDir;
super.init(persistSession, ignoreExpires);
}
_MyCookieStorage._internal();
}
class Singleton {
static final _options = BaseOptions(
baseUrl: BASE_URL,
followRedirects: true,
maxRedirects: 4,
);
static Dio _initializeDio() {
var dio = Dio(_options);
dio.interceptors.add(CookieManager(persistCookieJar));
dio.interceptors.add(_LogInterceptor());
return dio;
}
static final api = _initializeDio();
static final persistCookieJar = PersistCookieJar(storage: _MyCookieStorage());
static final Singleton _singleton = Singleton._internal();
Singleton._internal();
factory Singleton() {
return _singleton;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment