### Install Dio Package Source: https://pub.dev/documentation/dio/latest/index.html Add the dio package to your pubspec dependencies to start using it. ```yaml dependencies: dio: git: url: https://github.com/flutter/dio.git # Or specify a version # version: ^5.0.0 ``` -------------------------------- ### Super Simple Dio Usage Source: https://pub.dev/documentation/dio/latest/index.html Initialize Dio and make a basic GET request to a URL. Ensure the 'dio' instance is accessible. ```dart import 'package:dio/dio.dart'; final dio = Dio(); void getHttp() async { final response = await dio.get('https://dart.dev'); print(response); } ``` -------------------------------- ### Performing a GET Request with Dio Source: https://pub.dev/documentation/dio/latest/index.html Demonstrates making a GET request with query parameters, both directly and using a map. The response data is printed to the console. ```dart import 'package:dio/dio.dart'; final dio = Dio(); void request() async { Response response; response = await dio.get('/test?id=12&name=dio'); print(response.data.toString()); // The below request is the same as above. response = await dio.get( '/test', queryParameters: {'id': 12, 'name': 'dio'}, ); print(response.data.toString()); } ``` -------------------------------- ### Dio Instance Creation and Configuration Source: https://pub.dev/documentation/dio/latest/dio/Dio-class.html Demonstrates how to create a Dio instance with initial configurations like baseUrl, timeouts, and headers, and how to update these options later. ```APIDOC ## Dio Instance Creation and Configuration ### Description This section shows how to initialize a Dio instance with specific configurations and how to modify these configurations after the instance has been created. ### Creating a Dio instance with configurations: ```dart final dio = Dio( BaseOptions( baseUrl: "https://pub.dev", connectTimeout: const Duration(seconds: 5), receiveTimeout: const Duration(seconds: 5), headers: { HttpHeaders.userAgentHeader: 'dio', 'common-header': 'xx', }, ) ); ``` ### Updating Dio.options: ```dart dio.options.baseUrl = "https://pub.dev"; dio.options.connectTimeout = const Duration(seconds: 5); dio.options.receiveTimeout = const Duration(seconds: 5); ``` ### Constructors `Dio([BaseOptions? options])` Create the default Dio instance with the default implementation based on different platforms. factory ### Properties `httpClientAdapter` ↔ HttpClientAdapter The adapter that the instance is using. getter/setter pair `interceptors` → Interceptors Return the interceptors added into the instance. no setter `options` ↔ BaseOptions Default Request config. More see BaseOptions . getter/setter pair `transformer` ↔ Transformer Transformer allows changes to the request/response data before it is sent/received to/from the server. This is only applicable for requests that have payload. getter/setter pair ``` -------------------------------- ### Dio get Method Implementation Source: https://pub.dev/documentation/dio/latest/dio/DioMixin/get.html This is the implementation of the convenience get method in Dio. It simplifies making GET requests by internally calling the request method with the appropriate 'GET' option. ```dart @override Future> get( String path, { Map? queryParameters, Object? data, Options? options, CancelToken? cancelToken, ProgressCallback? onReceiveProgress, } ) { return request( path, data: data, queryParameters: queryParameters, options: checkOptions('GET', options), onReceiveProgress: onReceiveProgress, cancelToken: cancelToken, ); } ``` -------------------------------- ### Dio Instance Configuration Source: https://pub.dev/documentation/dio/latest/index.html Demonstrates how to create a singleton Dio instance and configure default settings like base URL, connection timeout, and receive timeout. It also shows alternative ways to initialize Dio with BaseOptions or by cloning an existing instance. ```APIDOC ## Dio Instance Configuration ### Description It is recommended to use a singleton of `Dio` in projects, which can manage configurations like headers, base urls, and timeouts consistently. Here is an example that use a singleton in Flutter. You can create instance of Dio with an optional `BaseOptions` object. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters N/A (Configuration) ### Request Example ```dart final dio = Dio(); // With default `Options`. void configureDio() { // Set default configs dio.options.baseUrl = 'https://api.pub.dev'; dio.options.connectTimeout = Duration(seconds: 5); dio.options.receiveTimeout = Duration(seconds: 3); // Or create `Dio` with a `BaseOptions` instance. final options = BaseOptions( baseUrl: 'https://api.pub.dev', connectTimeout: Duration(seconds: 5), receiveTimeout: Duration(seconds: 3), ); final anotherDio = Dio(options); // Or clone the existing `Dio` instance with all fields. final clonedDio = dio.clone(); } ``` ### Response N/A (Configuration) ``` -------------------------------- ### GET /uri Source: https://pub.dev/documentation/dio/latest/dio/DioMixin/getUri.html Makes an HTTP GET request using a provided Uri object. This is a convenience method that wraps the requestUri method for GET requests. ```APIDOC ## GET /uri ### Description Convenience method to make an HTTP GET request with Uri. ### Method GET ### Endpoint `/uri` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body for GET requests" } ``` ### Response #### Success Response (200) - **T** (type) - The type of the response data, determined by the generic type T. #### Response Example ```json { "example": "Response data of type T" } ``` ``` -------------------------------- ### BrowserHttpClientAdapter Constructor Source: https://pub.dev/documentation/dio/latest/browser/BrowserHttpClientAdapter-class.html Initializes a new instance of the BrowserHttpClientAdapter class. ```APIDOC ## BrowserHttpClientAdapter Constructor ### Description Initializes a new instance of the BrowserHttpClientAdapter class. ### Parameters #### Query Parameters - **withCredentials** (bool) - Optional - Whether to send credentials such as cookies or authorization headers for cross-site requests. ``` -------------------------------- ### GET /path Source: https://pub.dev/documentation/dio/latest/dio/DioMixin/get.html A convenience method to make an HTTP GET request. It abstracts the underlying request logic. ```APIDOC ## GET /path ### Description Convenience method to make an HTTP GET request. ### Method GET ### Endpoint /{path} ### Parameters #### Query Parameters - **queryParameters** (Map) - Optional - Additional query parameters to send with the request. - **cancelToken** (CancelToken) - Optional - Token to cancel the request. - **onReceiveProgress** (ProgressCallback) - Optional - Callback for receiving progress updates. #### Request Body This method does not typically use a request body for GET requests. ### Request Example ```dart // Example of calling the get method var response = await dio.get('/test', queryParameters: {'id': 123}); ``` ### Response #### Success Response (200) - **data** (T) - The decoded response data of type T. - **statusCode** (int) - The HTTP status code. - **headers** (Headers) - The response headers. - **requestOptions** (RequestOptions) - The request options used. - **isRedirect** (bool) - Whether the response was a redirect. - **redirects** (List) - Information about redirects. - **extra** (Map) - Extra data associated with the response. #### Response Example ```json { "data": "Success!", "statusCode": 200, "headers": { ... }, "requestOptions": { ... }, "isRedirect": false, "redirects": [], "extra": {} } ``` ``` -------------------------------- ### HttpClientAdapter Constructor Source: https://pub.dev/documentation/dio/latest/dio/HttpClientAdapter/HttpClientAdapter.html Creates a HttpClientAdapter based on the current platform (IO/Web). ```APIDOC ## HttpClientAdapter() ### Description Create a HttpClientAdapter based on the current platform (IO/Web). ### Method Factory Constructor ### Endpoint N/A ### Parameters None ### Request Example ```dart HttpClientAdapter adapter = HttpClientAdapter(); ``` ### Response #### Success Response (Instance of HttpClientAdapter) - **adapter** (HttpClientAdapter) - An instance of HttpClientAdapter configured for the current platform. ``` -------------------------------- ### GET Request Method Source: https://pub.dev/documentation/dio/latest/dio/Dio/get.html This method is a convenience wrapper for making HTTP GET requests. It supports various parameters for customization. ```APIDOC ## GET /path ### Description Convenience method to make an HTTP GET request. ### Method GET ### Endpoint /path ### Parameters #### Path Parameters - **path** (String) - Required - The endpoint path for the request. #### Query Parameters - **queryParameters** (Map) - Optional - Query parameters to append to the URL. #### Request Body - **data** (Object) - Optional - Data to be sent with the request (typically not used for GET requests but included for completeness). #### Options - **options** (Options) - Optional - Configuration options for the request. - **cancelToken** (CancelToken) - Optional - A token to cancel the request. - **onReceiveProgress** (ProgressCallback) - Optional - Callback for tracking download progress. ### Response #### Success Response (200) - **Response** - The response object containing the data of type T. #### Response Example ```json { "data": { ... }, "statusCode": 200, "statusMessage": "OK" } ``` ``` -------------------------------- ### MultipartFile Constructors Source: https://pub.dev/documentation/dio/latest/dio/MultipartFile-class.html This section covers the various ways to create a MultipartFile instance. ```APIDOC ## MultipartFile Constructors ### MultipartFile(Stream> stream, int length, {String? filename, DioMediaType? contentType, Map>? headers}) **Description**: Creates a new MultipartFile from a chunked Stream of bytes. The length of the file in bytes must be known in advance. If it's not, read the data from the stream and use MultipartFile.fromBytes instead. ### MultipartFile.fromBytes(List value, {String? filename, DioMediaType? contentType, Map>? headers}) **Description**: Creates a new MultipartFile from a byte array. ### MultipartFile.fromStream(Stream> data(), int length, {String? filename, DioMediaType? contentType, Map>? headers}) **Description**: Creates a new MultipartFile from a creation method that creates chunked Stream of bytes. The length of the file in bytes must be known in advance. If it's not, read the data from the stream and use MultipartFile.fromBytes instead. ### MultipartFile.fromString(String value, {String? filename, DioMediaType? contentType, Map>? headers}) **Description**: Creates a new MultipartFile from a string. ``` -------------------------------- ### GET /uri Source: https://pub.dev/documentation/dio/latest/dio/Dio/getUri.html Makes an HTTP GET request using a provided Uri. This is a convenience method that abstracts the underlying HTTP request logic. ```APIDOC ## GET /uri ### Description Convenience method to make an HTTP GET request with Uri. ### Method GET ### Endpoint /uri ### Parameters #### Path Parameters - **uri** (Uri) - Required - The Uri to make the GET request to. #### Query Parameters None explicitly defined for this method signature, but can be part of the `Uri` object. #### Request Body None ### Request Example ```json { "uri": "https://api.example.com/data", "data": { "param1": "value1" }, "options": { "headers": { "Authorization": "Bearer YOUR_TOKEN" } } } ``` ### Response #### Success Response (200) - **Response** (Future) - A Future that resolves to a Response object containing the data of type T. #### Response Example ```json { "data": { "key": "value" }, "statusCode": 200 } ``` ``` -------------------------------- ### Create Dio Instance with Configurations Source: https://pub.dev/documentation/dio/latest/dio/Dio-class.html Instantiate Dio with BaseOptions to set default configurations like baseUrl, connectTimeout, receiveTimeout, and common headers. This is useful for setting up a global HTTP client. ```dart final dio = Dio( BaseOptions( baseUrl: "https://pub.dev", connectTimeout: const Duration(seconds: 5), receiveTimeout: const Duration(seconds: 5), headers: { HttpHeaders.userAgentHeader: 'dio', 'common-header': 'xx', }, ) ); ``` -------------------------------- ### BrowserHttpClientAdapter Constructor Source: https://pub.dev/documentation/dio/latest/browser/BrowserHttpClientAdapter/BrowserHttpClientAdapter.html Information about the BrowserHttpClientAdapter constructor. ```APIDOC ## BrowserHttpClientAdapter constructor ### Description Initializes a new instance of the BrowserHttpClientAdapter class. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ## Implementation ```dart BrowserHttpClientAdapter({this.withCredentials = false}); ``` ### Parameters - **withCredentials** (bool) - Optional - Determines whether to include credentials with requests. ``` -------------------------------- ### HttpClientAdapter Class Overview Source: https://pub.dev/documentation/dio/latest/dio/HttpClientAdapter-class.html Provides an abstract overview of the HttpClientAdapter class, its purpose, and how it integrates with Dio. ```APIDOC ## HttpClientAdapter Class `HttpAdapter` is a bridge between Dio and HttpClient. Dio implements standard and friendly API for developer. HttpClient is the real object that makes Http requests. We can use any HttpClients not just "dart:io:HttpClient" to make the HTTP request. All we need is to provide a HttpClientAdapter. If you want to customize the HttpClientAdapter you should instead use either IOHttpClientAdapter on `dart:io` platforms or BrowserHttpClientAdapter on `dart:html` platforms. ### Implementers * IOHttpClientAdapter ``` -------------------------------- ### Get Object's Runtime Type Source: https://pub.dev/documentation/dio/latest/dio/OptionsMixin/runtimeType.html Use the runtimeType property to get the Type object representing the runtime type of an object. This is an external declaration. ```dart external Type get runtimeType; ``` -------------------------------- ### Update Dio get and getUri signatures Source: https://pub.dev/documentation/dio/latest/topics/Migration%20Guide-topic.html The `get` and `getUri` methods in `Dio` now accept an optional `Object? data` parameter. Ensure your calls are updated to reflect this signature change. ```dart Future> get( String path, { + Object? data, Map? queryParameters, Options? options, CancelToken? cancelToken, ProgressCallback? onReceiveProgress, }); ``` ```dart Future> getUri( Uri uri, { + Object? data, Map? queryParameters, Options? options, CancelToken? cancelToken, ProgressCallback? onReceiveProgress, }); ``` -------------------------------- ### Create and Configure Dio Singleton Source: https://pub.dev/documentation/dio/latest/index.html It is recommended to use a singleton Dio instance to manage configurations consistently across your project. You can create a Dio instance with default options or set configurations after creation. ```dart final dio = Dio(); // With default `Options`. void configureDio() { // Set default configs dio.options.baseUrl = 'https://api.pub.dev'; dio.options.connectTimeout = Duration(seconds: 5); dio.options.receiveTimeout = Duration(seconds: 3); // Or create `Dio` with a `BaseOptions` instance. final options = BaseOptions( baseUrl: 'https://api.pub.dev', connectTimeout: Duration(seconds: 5), receiveTimeout: Duration(seconds: 3), ); final anotherDio = Dio(options); // Or clone the existing `Dio` instance with all fields. final clonedDio = dio.clone(); } ``` -------------------------------- ### Example of noSuchMethod Invocation Source: https://pub.dev/documentation/dio/latest/dio/OptionsMixin/noSuchMethod.html This example demonstrates how accessing a non-existent method on a dynamic object triggers the noSuchMethod. The integer object's noSuchMethod is called with an Invocation representing the attempted call. ```dart dynamic object = 1; object.add(42); // Statically allowed, run-time error ``` -------------------------------- ### Implement getUri Method Source: https://pub.dev/documentation/dio/latest/dio/DioMixin/getUri.html This method is used to make an HTTP GET request with a Uri. It internally calls the requestUri method with the appropriate 'GET' option. Ensure Dio is properly configured before use. ```dart @override Future> getUri( Uri uri, { Object? data, Options? options, CancelToken? cancelToken, ProgressCallback? onReceiveProgress, } ) { return requestUri( uri, data: data, options: checkOptions('GET', options), onReceiveProgress: onReceiveProgress, cancelToken: cancelToken, ); } ``` -------------------------------- ### BrowserHttpClientAdapter Methods Source: https://pub.dev/documentation/dio/latest/browser/BrowserHttpClientAdapter-class.html Documentation for the methods available in the BrowserHttpClientAdapter class. ```APIDOC ## BrowserHttpClientAdapter Methods ### Description Methods available for the BrowserHttpClientAdapter class. #### Methods - **close** (void) - Closes the client. - **Parameters** - **force** (bool) - Optional - Whether to force the closure. - **fetch** (Future) - Implement this method to make real HTTP requests. - **Parameters** - **options** (RequestOptions) - Required - Options for the request. - **requestStream** (Stream?) - Optional - A stream of bytes for the request body. - **cancelFuture** (Future?) - Optional - A future that can be used to cancel the request. - **noSuchMethod** (dynamic) - Invoked when a nonexistent method or property is accessed. - **toString** (String) - A string representation of this object. ``` -------------------------------- ### Instantiate BrowserHttpClientAdapter Source: https://pub.dev/documentation/dio/latest/browser/BrowserHttpClientAdapter/BrowserHttpClientAdapter.html Use this constructor to create an instance of BrowserHttpClientAdapter. Set `withCredentials` to true if you need to send cookies or authorization headers. ```dart BrowserHttpClientAdapter({this.withCredentials = false}); ``` -------------------------------- ### Dio get Abstract Method Signature Source: https://pub.dev/documentation/dio/latest/dio/Dio/get.html Signature for the convenience method to make an HTTP GET request. It supports generic type T for response data, path, optional data, query parameters, options, cancellation token, and progress callbacks. ```dart Future> get( String path, { Object? data, Map? queryParameters, Options? options, CancelToken? cancelToken, ProgressCallback? onReceiveProgress, }); ``` -------------------------------- ### Download File with Progress Callback and Disabled Compression Source: https://pub.dev/documentation/dio/latest/browser/DioForBrowser/download.html Shows how to download a file, save it, disable gzip compression by setting 'accept-encoding' to '*', and monitor download progress. ```dart await dio.download( url, (await getTemporaryDirectory()).path + 'flutter.svg', options: Options( headers: {HttpHeaders.acceptEncodingHeader: '*'}, // Disable gzip ), onReceiveProgress: (received, total) { if (total <= 0) return; print('percentage: ${(received / total * 100).toStringAsFixed(0)}%'); }, ); ``` -------------------------------- ### Get Interceptors Source: https://pub.dev/documentation/dio/latest/dio/Dio/interceptors.html Retrieves the list of interceptors that have been added to the instance. ```APIDOC ## GET /interceptors ### Description Return the interceptors added into the instance. ### Method GET ### Endpoint /interceptors ### Parameters ### Request Body ### Request Example ### Response #### Success Response (200) - **interceptors** (Interceptors) - The list of interceptors. #### Response Example ```json { "interceptors": "Interceptors" } ``` ``` -------------------------------- ### GET contentType Source: https://pub.dev/documentation/dio/latest/dio/BaseOptions/contentType.html Retrieves the current Content-Type header value. ```APIDOC ## GET contentType ### Description Retrieves the current Content-Type header value from the request headers. ### Method GET ### Endpoint N/A (This is a property getter) ### Parameters None ### Response #### Success Response (200) - **contentType** (String?) - The value of the Content-Type header, or null if not set. ### Response Example ```json { "contentType": "application/json" } ``` ``` -------------------------------- ### MultipartFile Static Methods Source: https://pub.dev/documentation/dio/latest/dio/MultipartFile-class.html This section covers static methods for creating MultipartFile instances from files. ```APIDOC ## MultipartFile Static Methods ### MultipartFile.fromFile(String filePath, {String? filename, DioMediaType? contentType, Map>? headers}) **Description**: Creates a new MultipartFile from a path to a file on disk. ### MultipartFile.fromFileSync(String filePath, {String? filename, DioMediaType? contentType, Map>? headers}) **Description**: Creates a new MultipartFile synchronously from a path to a file on disk. ### MultipartFile.lookupMediaType(String? filenameOrPath) **Description**: Lookup the media type from the given `filenameOrPath` based on its extension. ``` -------------------------------- ### IOHttpClientAdapter Class Source: https://pub.dev/documentation/dio/latest/io The default HttpClientAdapter for native platforms. ```APIDOC ## IOHttpClientAdapter ### Description The default HttpClientAdapter for native platforms. ### Class IOHttpClientAdapter ``` -------------------------------- ### Get isFinalized Property Source: https://pub.dev/documentation/dio/latest/dio/FormData/isFinalized.html Returns a boolean indicating if finalize has been called. This is a getter implementation. ```dart bool get isFinalized => _isFinalized; ``` -------------------------------- ### Get sendTimeout Property Source: https://pub.dev/documentation/dio/latest/dio/BaseOptions/sendTimeout.html Retrieves the current value of the sendTimeout property. This is a getter method. ```dart Duration? get sendTimeout => _sendTimeout; ``` -------------------------------- ### QueuedInterceptor Constructors and Properties Source: https://pub.dev/documentation/dio/latest/dio/QueuedInterceptor-class.html Details the constructors and properties available for the QueuedInterceptor class. ```APIDOC ## Constructors QueuedInterceptor() ## Properties hashCode → int The hash code for this object. no setterinherited runtimeType → Type A representation of the runtime type of the object. no setterinherited ``` -------------------------------- ### IOHttpClientAdapter Constructor Source: https://pub.dev/documentation/dio/latest/io/IOHttpClientAdapter/IOHttpClientAdapter.html The IOHttpClientAdapter constructor allows for the creation of an HTTP client adapter with optional configurations for creating HTTP clients and validating certificates. ```APIDOC ## IOHttpClientAdapter Constructor ### Description Initializes an instance of the IOHttpClientAdapter. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **onHttpClientCreate** (OnHttpClientCreate?) - Deprecated - Use `createHttpClient` instead. This will be removed in 6.0.0. A callback function to create an HTTP client. - **createHttpClient** (CreateHttpClient?) - Optional - A callback function to create an HTTP client. - **validateCertificate** (ValidateCertificate?) - Optional - A callback function to validate SSL certificates. ### Request Example ```dart IOHttpClientAdapter( createHttpClient: (uri) => HttpClient(), validateCertificate: (cert, host, port) => true, ) ``` ### Response #### Success Response (200) N/A (This is a constructor) #### Response Example N/A ``` -------------------------------- ### Get Response Stream Source: https://pub.dev/documentation/dio/latest/index.html Retrieves the response body as a stream. Set `responseType` to `ResponseType.stream` in `Options`. ```dart final rs = await dio.get( url, options: Options(responseType: ResponseType.stream), // Set the response type to `stream`. ); print(rs.data.stream); // Response stream. ``` -------------------------------- ### Using ResponseType.stream Source: https://pub.dev/documentation/dio/latest/dio/ResponseType.html Use ResponseType.stream to get the response stream directly. The Response.data will be of type ResponseBody. ```dart Response rs = await Dio().get( url, options: Options(responseType: ResponseType.stream), ); ``` -------------------------------- ### IOHttpClientAdapter Constructors Source: https://pub.dev/documentation/dio/latest/io/IOHttpClientAdapter-class.html Details about the constructors available for the IOHttpClientAdapter class. ```APIDOC ## Constructors IOHttpClientAdapter({@Deprecated('Use createHttpClient instead. This will be removed in 6.0.0') OnHttpClientCreate? onHttpClientCreate, CreateHttpClient? createHttpClient, ValidateCertificate? validateCertificate}) ### Description Initializes a new instance of the IOHttpClientAdapter class. ### Parameters - **onHttpClientCreate** (OnHttpClientCreate?) - Optional - Dio will create HttpClient when it is needed. If onHttpClientCreate has provided, Dio will call it when a HttpClient created. Deprecated: Use createHttpClient instead. This will be removed in 6.0.0. - **createHttpClient** (CreateHttpClient?) - Optional - When this callback is set, Dio will call it every time it needs a HttpClient. - **validateCertificate** (ValidateCertificate?) - Optional - Allows the user to decide if the response certificate is good. If this function is missing, then the certificate is allowed. This method is called only if both the SecurityContext and `badCertificateCallback` accept the certificate chain. Those methods evaluate the root or intermediate certificate, while validateCertificate evaluates the leaf certificate. ``` -------------------------------- ### Get Interceptors Source: https://pub.dev/documentation/dio/latest/dio/Dio/interceptors.html Retrieve the interceptors that have been added to the instance. This property provides access to the configured interceptors. ```typescript Interceptors get interceptors; ``` -------------------------------- ### Download with Progress Callback Source: https://pub.dev/documentation/dio/latest/io/DioForNative/download.html Implement the download method to save a file from a URL, with options for progress callbacks, error handling, and file access modes. Ensure the response type is set to stream for efficient large file handling. ```dart @override Future download( String urlPath, dynamic savePath, { ProgressCallback? onReceiveProgress, Map? queryParameters, CancelToken? cancelToken, bool deleteOnError = true, FileAccessMode fileAccessMode = FileAccessMode.write, String lengthHeader = Headers.contentLengthHeader, Object? data, Options? options, }) async { options ??= DioMixin.checkOptions('GET', options); // Manually set the `responseType` to [ResponseType.stream] // to retrieve the response stream. // Do not modify previous options. options = options.copyWith(responseType: ResponseType.stream); final Response response; try { response = await request( urlPath, data: data, options: options, queryParameters: queryParameters, cancelToken: cancelToken, ); } on DioException catch (e) { if (e.type == DioExceptionType.badResponse) { final response = e.response!; if (response.requestOptions.receiveDataWhenStatusError == true) { final ResponseType implyResponseType; final contentType = response.headers.value(Headers.contentTypeHeader); if (contentType != null && contentType.startsWith('text/')) { implyResponseType = ResponseType.plain; } else { implyResponseType = ResponseType.json; } final res = await transformer.transformResponse( response.requestOptions.copyWith(responseType: implyResponseType), response.data as ResponseBody, ); response.data = res; } else { response.data = null; } } rethrow; } final File file; if (savePath is FutureOr Function(Headers)) { // Add real Uri and redirect information to headers. response.headers ..add('redirects', response.redirects.length.toString()) ..add('uri', response.realUri.toString()); file = File(await savePath(response.headers)); } else if (savePath is String) { file = File(savePath); } else { throw ArgumentError.value( savePath.runtimeType, 'savePath', 'The type must be `String` or `FutureOr Function(Headers)`. ); } // If the file already exists, the method fails. file.createSync(recursive: true); // Shouldn't call file.writeAsBytesSync(list, flush: flush), // because it can write all bytes by once. Consider that the file is // a very big size (up to 1 Gigabytes), it will be expensive in memory. RandomAccessFile raf = file.openSync( mode: fileAccessMode == FileAccessMode.write ? FileMode.write : FileMode.append, ); // Create a Completer to notify the success/error state. final completer = Completer(); int received = 0; // Stream final stream = response.data!.stream; bool compressed = false; int total = 0; final contentEncoding = response.headers.value( Headers.contentEncodingHeader, ); if (contentEncoding != null) { compressed = ['gzip', 'deflate', 'compress'].contains(contentEncoding); } if (lengthHeader == Headers.contentLengthHeader && compressed) { total = -1; } else { total = int.parse(response.headers.value(lengthHeader) ?? '-1'); } Future? asyncWrite; bool closed = false; Future closeAndDelete() async { if (!closed) { closed = true; await asyncWrite; await raf.close().catchError((_) => raf); if (deleteOnError && file.existsSync()) { await file.delete().catchError((_) => file); } } } late StreamSubscription subscription; subscription = stream.listen( (data) { subscription.pause(); // Write file asynchronously asyncWrite = raf.writeFrom(data).then((result) { // Notify progress received += data.length; onReceiveProgress?.call(received, total); raf = result; if (cancelToken == null || !cancelToken.isCancelled) { subscription.resume(); } }).catchError((Object e) async { try { await subscription.cancel().catchError((_) {}); closed = true; await raf.close().catchError((_) => raf); if (deleteOnError && file.existsSync()) { await file.delete().catchError((_) => file); } } finally { completer.completeError( DioMixin.assureDioException(e, response.requestOptions), ); } }); }, onDone: () async { try { await asyncWrite; closed = true; await raf.close().catchError((_) => raf); completer.complete(response); } catch (e) { completer.completeError( DioMixin.assureDioException(e, response.requestOptions), ); } }, onError: (e) async { try { await closeAndDelete(); } finally { completer.completeError( ``` -------------------------------- ### Get Response with Bytes Source: https://pub.dev/documentation/dio/latest/index.html Retrieves the response body as a list of bytes. Set `responseType` to `ResponseType.bytes` in `Options`. ```dart final rs = await Dio().get>( url, options: Options(responseType: ResponseType.bytes), // Set the response type to `bytes`. ); print(rs.data); // Type: List. ``` -------------------------------- ### Download Methods Source: https://pub.dev/documentation/dio/latest/browser/DioForBrowser-class.html Methods for downloading files to local storage. ```APIDOC ## POST /download ### Description Download the file and save it in local. The default http method is "GET", you can custom it by Options.method. ### Method POST (default GET, customizable) ### Endpoint /{urlPath} ### Parameters #### Path Parameters - **urlPath** (String) - Required - The URL path of the file to download. - **savePath** (dynamic) - Required - The local path to save the downloaded file. #### Query Parameters - **queryParameters** (Map) - Optional - Query parameters to append to the URL. - **cancelToken** (CancelToken?) - Optional - Token to cancel the request. - **deleteOnError** (bool) - Optional - Whether to delete the file if an error occurs (default: true). - **fileAccessMode** (FileAccessMode) - Optional - The file access mode (default: FileAccessMode.write). - **lengthHeader** (String) - Optional - The header to use for content length (default: Headers.contentLengthHeader). - **data** (Object?) - Optional - Request body data. - **options** (Options?) - Optional - Request options. - **onReceiveProgress** (ProgressCallback?) - Optional - Callback for download progress. ### Response #### Success Response (200) - **Response** - The response object. ## POST /downloadUri ### Description Download the file and save it in local using a Uri. The default http method is "GET", you can custom it by Options.method. ### Method POST (default GET, customizable) ### Endpoint /{uri} ### Parameters #### Path Parameters - **uri** (Uri) - Required - The Uri of the file to download. - **savePath** (dynamic) - Required - The local path to save the downloaded file. #### Query Parameters - **cancelToken** (CancelToken?) - Optional - Token to cancel the request. - **deleteOnError** (bool) - Optional - Whether to delete the file if an error occurs (default: true). - **fileAccessMode** (FileAccessMode) - Optional - The file access mode (default: FileAccessMode.write). - **lengthHeader** (String) - Optional - The header to use for content length (default: Headers.contentLengthHeader). - **data** (Object?) - Optional - Request body data. - **options** (Options?) - Optional - Request options. - **onReceiveProgress** (ProgressCallback?) - Optional - Callback for download progress. ### Response #### Success Response (200) - **Response** - The response object. ``` -------------------------------- ### Get connectTimeout Source: https://pub.dev/documentation/dio/latest/dio/Options/connectTimeout.html Retrieves the current connection timeout duration. `null` or `Duration.zero` indicates no timeout limit. ```dart Duration? get connectTimeout => _connectTimeout; ``` -------------------------------- ### Download Methods Source: https://pub.dev/documentation/dio/latest/io/DioForNative-class.html Methods for downloading files to local storage. ```APIDOC ## POST /download ### Description Download the file and save it in local. The default http method is "GET", you can custom it by Options.method. ### Method POST (default GET, customizable) ### Endpoint `/download` ### Parameters #### Path Parameters - **urlPath** (String) - Required - The URL path of the file to download. - **savePath** (dynamic) - Required - The local path to save the downloaded file. #### Query Parameters - **queryParameters** (Map) - Optional - Query parameters to be sent with the request. - **cancelToken** (CancelToken?) - Optional - Token to cancel the request. - **deleteOnError** (bool) - Optional - Whether to delete the file if an error occurs (default: true). - **fileAccessMode** (FileAccessMode) - Optional - The file access mode (default: FileAccessMode.write). - **lengthHeader** (String) - Optional - The header to use for file length (default: Headers.contentLengthHeader). - **data** (Object?) - Optional - Request body data. - **options** (Options?) - Optional - Request options. - **onReceiveProgress** (ProgressCallback?) - Optional - Callback for receiving progress updates. ### Response #### Success Response (200) - **Response** - The response object. ## POST /downloadUri ### Description Download the file and save it in local using a Uri. The default http method is "GET", you can custom it by Options.method. ### Method POST (default GET, customizable) ### Endpoint `/downloadUri` ### Parameters #### Path Parameters - **uri** (Uri) - Required - The Uri of the file to download. - **savePath** (dynamic) - Required - The local path to save the downloaded file. #### Query Parameters - **cancelToken** (CancelToken?) - Optional - Token to cancel the request. - **deleteOnError** (bool) - Optional - Whether to delete the file if an error occurs (default: true). - **fileAccessMode** (FileAccessMode) - Optional - The file access mode (default: FileAccessMode.write). - **lengthHeader** (String) - Optional - The header to use for file length (default: Headers.contentLengthHeader). - **data** (Object?) - Optional - Request body data. - **options** (Options?) - Optional - Request options. - **onReceiveProgress** (ProgressCallback?) - Optional - Callback for receiving progress updates. ### Response #### Success Response (200) - **Response** - The response object. ``` -------------------------------- ### HttpClientAdapter Constructors Source: https://pub.dev/documentation/dio/latest/dio/HttpClientAdapter-class.html Details on the constructors available for the HttpClientAdapter class. ```APIDOC ## Constructors ### HttpClientAdapter() Create a HttpClientAdapter based on the current platform (IO/Web). `factory` ``` -------------------------------- ### Get cancelError Property Source: https://pub.dev/documentation/dio/latest/dio/CancelToken/cancelError.html This getter retrieves the cancel error if the request was canceled. It is null if the request was not canceled. ```dart DioException? get cancelError => _cancelError; ``` -------------------------------- ### Get receiveTimeout Property Source: https://pub.dev/documentation/dio/latest/dio/BaseOptions/receiveTimeout.html Retrieves the current value of the receiveTimeout. This is a getter method for the private _receiveTimeout variable. ```dart Duration? get receiveTimeout => _receiveTimeout; ``` -------------------------------- ### OnHttpClientCreate Typedef Source: https://pub.dev/documentation/dio/latest/io Signature for customizing HttpClient creation. ```APIDOC ## OnHttpClientCreate ### Description The signature of IOHttpClientAdapter.onHttpClientCreate. Allows for custom HttpClient creation logic. ### Typedef OnHttpClientCreate = HttpClient? Function(HttpClient client) ``` -------------------------------- ### Get Headers Property Source: https://pub.dev/documentation/dio/latest/dio/BaseOptions/headers.html Retrieves the current headers map. This getter returns the internal _headers map. ```dart Map get headers => _headers; ``` -------------------------------- ### MultipartFile Methods Source: https://pub.dev/documentation/dio/latest/dio/MultipartFile-class.html Available methods for interacting with a MultipartFile instance. ```APIDOC ## MultipartFile Methods ### clone() → MultipartFile **Description**: Clone MultipartFile, returning a new instance of the same object. This is useful if your request failed and you wish to retry it, such as an unauthorized exception can be solved by refreshing the token. ### finalize() → Stream **Description**: Finalizes the multipart file stream. ``` -------------------------------- ### Get contentType Source: https://pub.dev/documentation/dio/latest/dio/BaseOptions/contentType.html Retrieves the current value of the content type header. Returns null if the header is not set. ```dart String? get contentType => _headers[Headers.contentTypeHeader] as String?; ``` -------------------------------- ### QueuedInterceptor Methods Source: https://pub.dev/documentation/dio/latest/dio/QueuedInterceptor-class.html Lists the methods available for the QueuedInterceptor class, including request, response, and error handling. ```APIDOC ## Methods noSuchMethod(Invocation invocation) → dynamic Invoked when a nonexistent method or property is accessed. inherited onError(DioException err, ErrorInterceptorHandler handler) → void Called when an exception was occurred during the request. inherited onRequest(RequestOptions options, RequestInterceptorHandler handler) → void Called when the request is about to be sent. inherited onResponse(Response response, ResponseInterceptorHandler handler) → void Called when the response is about to be resolved. inherited toString() → String A string representation of this object. inherited ``` -------------------------------- ### Get Response Content Length Source: https://pub.dev/documentation/dio/latest/dio/ResponseBody/contentLength.html Retrieves the content length from the response headers. Returns -1 if the header is not present. ```dart int get contentLength => int.parse(headers[Headers.contentLengthHeader]?.first ?? '-1'); ``` -------------------------------- ### MultipartFile.fromFileSync Source: https://pub.dev/documentation/dio/latest/dio/MultipartFile/fromFileSync.html Creates a MultipartFile instance from a local file synchronously. ```APIDOC ## MultipartFile.fromFileSync ### Description Creates a `MultipartFile` instance from a local file synchronously. This method is useful for uploading files from the local file system. ### Method `static MultipartFile fromFileSync(String filePath, {String? filename, DioMediaType? contentType, Map>? headers})` ### Parameters #### Path Parameters - **filePath** (String) - Required - The path to the file to be uploaded. #### Optional Parameters - **filename** (String?) - Optional - The name of the file to be used in the multipart request. If not provided, the filename will be extracted from the `filePath`. - **contentType** (DioMediaType?) - Optional - The content type of the file. If not provided, it will be inferred from the file extension. - **headers** (Map>?) - Optional - Additional headers to be included in the multipart request for this file. ### Request Example ```dart // Example of creating a MultipartFile from a file var file = await MultipartFile.fromFileSync('/path/to/your/file.jpg', filename: 'upload.jpg'); ``` ### Response #### Success Response (MultipartFile) Returns a `MultipartFile` object that can be used in a Dio request. #### Response Example ```dart // The returned object is a MultipartFile instance // Example usage in a Dio request: // dio.post('/upload', data: FormData.fromMap({'file': file})); ``` ``` -------------------------------- ### onResponse Method Source: https://pub.dev/documentation/dio/latest/dio/Interceptor/onResponse.html The onResponse method is a callback that gets executed when a response is about to be resolved. It allows for intercepting and modifying responses. ```APIDOC ## onResponse Method ### Description Called when the response is about to be resolved. This method is part of Dio's interceptor mechanism, allowing you to perform actions before a response is finalized. ### Parameters - **response** (Response) - The response object received from the server. - **handler** (ResponseInterceptorHandler) - The handler to manage the response lifecycle, allowing to proceed or modify the response. ### Implementation Example ```dart void onResponse( Response response, ResponseInterceptorHandler handler, ) { // Process the response here, e.g., logging, data transformation handler.next(response); // Continue with the response processing } ``` ``` -------------------------------- ### IOHttpClientAdapter Constructor Implementation Source: https://pub.dev/documentation/dio/latest/io/IOHttpClientAdapter/IOHttpClientAdapter.html Provides the implementation of the IOHttpClientAdapter constructor, assigning the provided parameters to the instance variables. ```dart IOHttpClientAdapter({ @Deprecated('Use createHttpClient instead. This will be removed in 6.0.0') this.onHttpClientCreate, this.createHttpClient, this.validateCertificate, }); ``` -------------------------------- ### Download File with Progress Callback Source: https://pub.dev/documentation/dio/latest/dio/DioMixin/downloadUri.html Download a file and save it locally, with an option to disable gzip compression for accurate progress reporting. Use this when you need to monitor download progress and ensure the 'total' value in the callback is not -1. ```dart await dio.download( url, (await getTemporaryDirectory()).path + 'flutter.svg', options: Options( headers: {HttpHeaders.acceptEncodingHeader: '*'}, // Disable gzip ), onReceiveProgress: (received, total) { if (total <= 0) return; print('percentage: ${(received / total * 100).toStringAsFixed(0)}%'); }, ); ``` -------------------------------- ### Get Map Property Implementation Source: https://pub.dev/documentation/dio/latest/dio/Headers/map.html Provides the getter implementation for the 'map' property. This is used to access the internal map. ```dart Map> get map => _map; ``` -------------------------------- ### External int get hashCode Source: https://pub.dev/documentation/dio/latest/dio/OptionsMixin/hashCode.html This is the external declaration for the hashCode property. It indicates that the implementation is provided by the underlying platform or runtime. ```dart external int get hashCode; ``` -------------------------------- ### QueuedInterceptor Constructor Source: https://pub.dev/documentation/dio/latest/dio/QueuedInterceptor/QueuedInterceptor.html Initializes a new instance of the QueuedInterceptor class. ```APIDOC ## QueuedInterceptor() ### Description Initializes a new instance of the QueuedInterceptor class. ### Method Constructor ### Endpoint N/A ### Parameters This constructor does not accept any parameters. ### Request Example ```json { "example": "QueuedInterceptor()" } ``` ### Response #### Success Response (200) N/A (Constructors do not return values in the traditional sense). #### Response Example N/A ``` -------------------------------- ### Get List Length Source: https://pub.dev/documentation/dio/latest/dio/Interceptors/length.html Retrieves the number of elements currently in the list. The valid indices range from 0 to length - 1. ```APIDOC ## GET /list/length ### Description Retrieves the number of objects in this list. ### Method GET ### Endpoint /list/length ### Parameters None ### Request Body None ### Response #### Success Response (200) - **length** (int) - The number of elements in the list. #### Response Example ```json { "length": 3 } ``` ``` -------------------------------- ### QueuedInterceptor Class Overview Source: https://pub.dev/documentation/dio/latest/dio/QueuedInterceptor-class.html Provides an overview of the QueuedInterceptor class, its purpose, and inheritance. ```APIDOC ## QueuedInterceptor Class Interceptor in queue. `onRequest`, `onResponse`, and `onError` are processed in separate queues when running concurrent requests. These queues run in parallel, new requests can be initiated before previous have been completed. ### Inheritance * Object * Interceptor * QueuedInterceptor ### Implementers * QueuedInterceptorsWrapper ``` -------------------------------- ### Accessing the whenCancel Future Source: https://pub.dev/documentation/dio/latest/dio/CancelToken/whenCancel.html Use this property to get a Future that will be resolved when the request is cancelled. It returns a DioException upon cancellation. ```dart Future get whenCancel => _completer.future; ``` -------------------------------- ### Performing Multiple Concurrent Requests Source: https://pub.dev/documentation/dio/latest/index.html Utilizes `Future.wait` to execute multiple Dio requests (POST and GET) concurrently and collect all responses. ```dart List responses = await Future.wait([dio.post('/info'), dio.get('/token')]); ``` -------------------------------- ### IOHttpClientAdapter Methods Source: https://pub.dev/documentation/dio/latest/io/IOHttpClientAdapter-class.html Details about the methods available for the IOHttpClientAdapter class. ```APIDOC ## Methods ### close - **Signature**: close({bool force = false}) → void - **Description**: Close the current adapter and its inner clients or requests. - **Override**: true - **Parameters**: - **force** (bool) - Optional - Defaults to false. Indicates if the closing should be forceful. ### fetch - **Signature**: fetch(RequestOptions options, Stream? requestStream, Future? cancelFuture) → Future - **Description**: Implement this method to make real HTTP requests. - **Override**: true - **Parameters**: - **options** (RequestOptions) - Required - The request options. - **requestStream** (Stream?) - Optional - The stream for the request body. - **cancelFuture** (Future?) - Optional - A future that can be used to cancel the request. ### noSuchMethod - **Signature**: noSuchMethod(Invocation invocation) → dynamic - **Description**: Invoked when a nonexistent method or property is accessed. - **Inherited**: true ``` -------------------------------- ### Initialize HttpClientAdapter in Dio Source: https://pub.dev/documentation/dio/latest/topics/Migration%20Guide-topic.html Before version 5.0.0, `DefaultHttpClientAdapter` and `BrowserHttpClientAdapter` were used directly. Now, `HttpClientAdapter()` acts as a factory for the platform-independent adapter, and `IOHttpClientAdapter` is used for native platforms. ```dart void initAdapter() { final dio = Dio(); // For natives. dio.httpClientAdapter = DefaultHttpClientAdapter(); // For web. dio.httpClientAdapter = BrowserHttpClientAdapter(); } ``` ```dart void initAdapter() { final dio = Dio(); // Universal adapter that create the adapter for the corresponding platform. dio.httpClientAdapter = HttpClientAdapter(); // For natives. dio.httpClientAdapter = IOHttpClientAdapter(); // For web. dio.httpClientAdapter = BrowserHttpClientAdapter(); } ``` -------------------------------- ### Response Constructor Implementation Source: https://pub.dev/documentation/dio/latest/dio/Response/Response.html Provides the implementation for the Response constructor, initializing its properties and handling default values for headers and extra data. ```dart Response({ this.data, required this.requestOptions, this.statusCode, this.statusMessage, this.isRedirect = false, this.redirects = const [], Map? extra, Headers? headers, }) : headers = headers ?? Headers(preserveHeaderCase: requestOptions.preserveHeaderCase), extra = extra ?? {}; ```