first commit
This commit is contained in:
86
lib/service/dio.dart
Normal file
86
lib/service/dio.dart
Normal file
@@ -0,0 +1,86 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../constants/api_constants.dart';
|
||||
|
||||
class CustomDio {
|
||||
final Dio _dio = Dio(
|
||||
BaseOptions(
|
||||
baseUrl: ApiConstants.baseUrl, // Change this to your API base URL
|
||||
connectTimeout: Duration(seconds: 20), // Timeout settings
|
||||
receiveTimeout: Duration(seconds: 40),
|
||||
headers: {'Content-Type': 'application/json'}, // Default headers
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
Future<dynamic> getData(
|
||||
String endpoint, {
|
||||
Map<String, dynamic>? headers,
|
||||
}) async {
|
||||
try {
|
||||
Response response = await _dio.get(
|
||||
endpoint,
|
||||
options: Options(headers: headers),
|
||||
);
|
||||
|
||||
return response.data;
|
||||
} on DioException catch (e) {
|
||||
// 🔥 THIS IS THE FIX
|
||||
if (e.response != null) {
|
||||
print("ERROR DATA: ${e.response?.data}");
|
||||
return e.response?.data; // ✅ return actual backend response
|
||||
} else {
|
||||
print("DIO ERROR: ${e.message}");
|
||||
return null;
|
||||
}
|
||||
} catch (e) {
|
||||
print("UNKNOWN ERROR: $e");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// POST Request
|
||||
Future<dynamic> postData(String endpoint, Map<String, dynamic> data) async {
|
||||
try {
|
||||
Response response = await _dio.post(endpoint, data: data);
|
||||
return response.data;
|
||||
} catch (e) {
|
||||
return _handleError(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// PUT Request
|
||||
Future<dynamic> putData(String endpoint, Map<String, dynamic> data) async {
|
||||
try {
|
||||
Response response = await _dio.put(endpoint, data: data);
|
||||
return response.data;
|
||||
} catch (e) {
|
||||
return _handleError(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// DELETE Request
|
||||
Future<dynamic> deleteData(String endpoint) async {
|
||||
try {
|
||||
Response response = await _dio.delete(endpoint);
|
||||
return response.data;
|
||||
} catch (e) {
|
||||
return _handleError(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle Errors
|
||||
dynamic _handleError(dynamic error) {
|
||||
if (error is DioException) {
|
||||
return "Error: ${error.message}";
|
||||
}
|
||||
return "Unexpected Error";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user