Versatile HTTP Requests with Dio in Flutter
Dio is a popular HTTP client library for Flutter, offering a versatile core method request() that handles all standard HTTP operations like GET, POST, PUT, and DELETE. This method serves as a unified entry point, eliminating the need to switch between separate method-specific functions for different request types.
The request() method signature inclueds several key parameters:
url: Target API endpoint address.data: Request body content (typically used for POST/PUT/PATCH).queryParameters: Query string parameters appended to the URL.options: Configures critical request details, most importantly the HTTP method type.cancelToken: Enables request cancellation.onSendProgress/onReceiveProgress: Track upload/download progress.
To simplify usage, request() can be wrapped into a reusable helper function with predefined defaults or dynamic configurations. The example below demonstrates a GET request wrapper:
import 'package:dio/dio.dart';
class NetworkService {
final Dio _dioInstance = Dio();
Future<dynamic> sendGenericRequest(
String endpoint, {
required Map<String, dynamic> queryArgs,
String requestMethod = 'GET',
}) async {
final requestOptions = Options(method: requestMethod);
try {
final response = await _dioInstance.request(
endpoint,
queryParameters: queryArgs,
options: requestOptions,
);
return response.data;
} on DioException catch (error) {
print('Network request failed: ${error.message}');
return Future.error(error);
}
}
}
In this wrapper, we initialize a Dio instance within a NetworkService class for reusability. The sendGenericRequest method accepts an endpoint, query parameters, and an optional HTTP method (defaulting to GET). The Options object configures the request type, and error handling catches Dio-specific exceptions.