post method

Future<Response> post(
  1. String endpoint, {
  2. required dynamic body,
  3. dynamic query,
  4. dynamic customheader,
})

Sends an HTTP POST request to the specified endpoint.

This method wraps the Dio POST request, allowing for a request body, optional query parameters, and custom headers. Any exceptions encountered during the request will be re-thrown.

To create a new user with an authorization header:

try {
  final newUser = {'name': 'John Doe', 'email': 'john.doe@example.com'};
  final response = await apiService.post(
    '/users',
    body: newUser,
    customheader: {'Authorization': 'Bearer your_token'},
  );
  print('User created with ID: ${response.data['id']}');
} on DioException catch (e) {
  print('Error creating user: $e');
}

Parameters:

  • endpoint: The URL path or the full URL for the request (e.g., '/users').
  • body: The request body, required. Can be a Map, List, String, etc.
  • query: Optional query parameters. Typically a Map<String, dynamic>.
  • customheader: Optional custom headers. Typically a Map<String, String>.

Returns:

  • A Future<Response> that completes with the server's response.

Throws:

  • Any DioException (or other exceptions) that occur during the request.

Implementation

Future<Response> post(String endpoint,
    {required dynamic body, dynamic query, dynamic customheader}) async {
  try {
    return await _dio.post(
      endpoint,
      data: body,
      queryParameters: query,
      options: Options(headers: customheader),
    );
  } catch (e) {
    rethrow;
  }
}