Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KingsleyUsoroeno/87bc3e4e696c06f5a58c9071ef2c1699 to your computer and use it in GitHub Desktop.
Save KingsleyUsoroeno/87bc3e4e696c06f5a58c9071ef2c1699 to your computer and use it in GitHub Desktop.
Flutter Dio helper class
Future<Dio> getInstance() async {
final String token =
await fluxPreference.readString(PreferenceConstants.USER_TOKEN, null);
Map<String, dynamic> headers = {};
headers['Content-Type'] = 'application/json';
headers['RESPONSE-VERSION'] = '2';
if (token != null) headers['Authorization'] = 'Bearer $token';
print("Token ============================ $token");
return Dio(BaseOptions(
baseUrl: baseUrl,
responseType: ResponseType.json,
connectTimeout: 30000,
receiveTimeout: 30000,
))
..options.headers = headers
..interceptors.addAll([
LoggingInterceptor.loggingInterceptor(),
]);
}
Future<Response> get(String url) async {
try {
final client = await getInstance();
return await client.get(url);
} on DioError catch (e) {
// Handle error
throw Exception(e.message);
} catch (e) {
throw Exception(e.toString());
}
}
Future<Response> post(String url, dynamic data) async {
try {
final client = await getInstance();
return await client.post(url, data: data);
} on DioError catch (e) {
// Handle error
throw Exception(e.message);
} catch (e) {
throw Exception(e.toString());
}
}
Future<Response> put(String url, dynamic data) async {
try {
final client = await getInstance();
return await client.put(url, data: data);
} on DioError catch (e) {
throw Exception(e.message);
} catch (e) {
throw Exception(e.toString());
}
}
Future<Response> delete(String url) async {
try {
final client = await getInstance();
return await client.delete(url);
} on DioError catch (e) {
throw Exception(e.message);
} catch (e) {
throw Exception(e.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment