import 'dart:convert';
import 'dart:io';
import 'package:dio/[Link]';
class RestAPI {
late Dio _dio;
RestAPI() {
_dio = Dio();
}
Future<Map<String, dynamic>> getRequest(String url,
{Map<String, dynamic>? headers}) async {
Options options = Options(
headers: headers,
);
try {
var response = await _dio.getUri([Link](url), options: options);
print('The get response from the url: [$url] is ${[Link]}');
if ([Link] == 200) {
return [Link]([Link]);
} else {
throw Exception('Failed to load data');
}
} catch (e) {
DioException exception = e as DioException;
if ([Link] != null) {
return [Link]([Link]!.data);
}
rethrow;
}
}
Future<Map<String, dynamic>> postRequest(String url,
{Map<String, dynamic>? headers, Map<String, dynamic>? body}) async {
Options options = Options(
headers: headers,
);
try {
var response = await _dio.postUri(
[Link](url),
options: options,
data: body,
);
print('The post response from the url: [$url] is ${[Link]}');
if ([Link] == 200) {
return [Link]([Link]);
} else {
throw Exception('Failed to load data');
}
} catch (e) {
DioException exception = e as DioException;
if ([Link] != null) {
return [Link]([Link]!.data);
}
rethrow;
}
}
Future<Map<String, dynamic>> uploadPostRequest(String url,
{Map<String, dynamic>? headers,
required Map<String, File>? files,
Map<String, dynamic>? body}) async {
try {
final formData = FormData();
if (body != null) {
[Link]((key, value) {
// Handle list types by converting to JSON string
if (value is List) {
[Link](MapEntry(key, jsonEncode(value)));
} else {
[Link](MapEntry(key, [Link]()));
}
});
}
// Add files
if (files != null) {
for (var entry in [Link]) {
[Link](MapEntry(
[Link],
await [Link](
[Link],
filename: [Link], // UUID filename
),
));
}
}
var response = await _dio.postUri(
[Link](url),
options: Options(headers: headers),
data: formData,
);
print('The post response from the url: [$url] is ${[Link]}');
if ([Link] == 200) {
return [Link];
} else {
throw Exception('Failed to load data');
}
} catch (e) {
print('[DEBUG] Error: $e');
DioException exception = e as DioException;
if ([Link] != null) {
return [Link]([Link]!.data);
}
rethrow;
}
}
}