Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Versatile HTTP Requests with Dio in Flutter

Tech 1

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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.