Skip to content

Instantly share code, notes, and snippets.

@ponnamkarthik
Created May 29, 2021 07:12
Show Gist options
  • Save ponnamkarthik/e6cc4e414cc28210e0217ad1dcdfcb89 to your computer and use it in GitHub Desktop.
Save ponnamkarthik/e6cc4e414cc28210e0217ad1dcdfcb89 to your computer and use it in GitHub Desktop.
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:helpservice/utils/constants.dart';
import 'package:shared_preferences/shared_preferences.dart';
class DioClient {
factory DioClient() {
return _singleton;
}
DioClient._internal() {
if (_dio == null) {
init();
}
}
static final DioClient _singleton = DioClient._internal();
Dio _dio;
Dio _tokenDio;
String token;
static SharedPreferences sharedPrefs;
Future<String> _getAuthorizationToken() async {
if (sharedPrefs == null) {
await _setUpSharedPrefs();
}
token = sharedPrefs.getString('token');
print(token);
return token ?? '';
}
Future<void> _setUpSharedPrefs() async {
sharedPrefs = await SharedPreferences.getInstance();
}
dynamic init() {
_setUpSharedPrefs();
_dio = Dio();
_dio.options = BaseOptions(
validateStatus: (status) => status <= 500,
baseUrl: Constants.baseUrl,
);
// Used to get token
_tokenDio = Dio();
_tokenDio.options = BaseOptions(
validateStatus: (status) => status < 500,
baseUrl: Constants.baseUrl,
);
_tokenDio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) async {
return handler.next(options);
},
),
);
_dio.interceptors
.add(InterceptorsWrapper(onRequest: (options, handler) async {
options.headers['Accept'] = 'application/json';
final token = await _getAuthorizationToken();
options.queryParameters['wstoken'] = "$token";
options.queryParameters['moodlewsrestformat'] = 'json';
// options.queryParameters['service'] = 'moodle_mobile_app';
return handler.next(options);
}, onResponse: (response, handler) async {
// Do something with response data
// TODO: Remove Print Statements
debugPrint(response.requestOptions.uri.toString());
debugPrint(response.statusCode.toString());
print(response.data);
handler.next(response);
}, onError: (error, handler) async {
// TODO: Remove Print Statements
debugPrint('Error');
debugPrint(error?.response?.requestOptions?.uri.toString());
debugPrint(error?.response?.statusCode?.toString() ?? '');
handler.next(error);
}));
}
Dio get ref => _dio;
Dio get tokenRef => _tokenDio;
}
final dioClient = DioClient();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment