### FetchClient HTTP Methods (GET, POST, PUT, DELETE, PATCH) Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient-class Provides convenient methods for sending specific HTTP request types (GET, POST, PUT, DELETE, PATCH). These methods abstract the creation of BaseRequest objects and simplify common request patterns. They return a Future that completes with the Response object. ```dart Future get(Uri url, {Map? headers}) Future post(Uri url, {Map? headers, Object? body, Encoding? encoding}) Future put(Uri url, {Map? headers, Object? body, Encoding? encoding}) Future delete(Uri url, {Map? headers, Object? body, Encoding? encoding}) Future patch(Uri url, {Map? headers, Object? body, Encoding? encoding}) ``` -------------------------------- ### Implement readBytes Method in Dart Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/readBytes This Dart code demonstrates how to implement the `readBytes` method. It sends an HTTP GET request using the `get` function, checks for a successful response status, and returns the response body as a `Uint8List`. Dependencies include the `http` package for network requests and a helper function `_checkResponseSuccess` for error handling. ```dart @override Future readBytes(Uri url, {Map? headers}) async { final response = await get(url, headers: headers); _checkResponseSuccess(url, response); return response.bodyBytes; } ``` -------------------------------- ### Implement HTTP GET Request with Read Method - Dart Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/read This Dart code snippet demonstrates the implementation of the `read` method. It sends an HTTP GET request to a specified URL with optional headers and returns the response body. The method relies on the `get` function and includes a check for successful response status codes. ```dart @override Future read(Uri url, {Map? headers}) async { final response = await get(url, headers: headers); _checkResponseSuccess(url, response); return response.body; } ``` -------------------------------- ### FetchClient.read and readBytes Methods Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient-class Convenience methods for sending HTTP GET requests and retrieving the response body as a String or a Uint8List, respectively. These methods are useful for directly accessing the content of a response without manually parsing it. They also handle potential errors during the request. ```dart Future read(Uri url, {Map? headers}) Future readBytes(Uri url, {Map? headers}) ``` -------------------------------- ### Implement toString Method in Dart Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/RequestMode/toString This snippet demonstrates the implementation of the 'toString' method in Dart. It overrides the default method to return a custom string representation, often used for debugging or logging purposes. The example shows returning the value of the 'mode' variable. ```dart @override String toString() => mode; ``` -------------------------------- ### Get contentLength Property (Dart) Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchRequest/contentLength This snippet shows the implementation for getting the contentLength property. It overrides the default getter to return the contentLength from the underlying request object. The property returns an integer representing the body size in bytes, or null if the size is not known. ```dart @override int? get contentLength => request.contentLength; ``` -------------------------------- ### Get maxRedirects Property (Dart) Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchRequest/maxRedirects Retrieves the maximum number of redirects allowed. If this limit is exceeded while followRedirects is true, a ClientException is thrown. Defaults to 5. ```dart @override int get maxRedirects => request.maxRedirects; ``` -------------------------------- ### FetchResponse Constructor Implementation Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchResponse/FetchResponse Shows the implementation of the FetchResponse constructor, which initializes the response object by calling the superclass constructor with the provided arguments. It highlights how parameters are assigned to the corresponding fields. ```dart FetchResponse(super.stream, super.statusCode, { required this.cancel, required this.url, required this.redirected, super.contentLength, super.request, super.headers, super.isRedirect, super.persistentConnection, super.reasonPhrase, }); ``` -------------------------------- ### FetchClient Constructor (Dart) Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/FetchClient Initializes a new FetchClient instance using the Fetch API. It allows configuration of request mode, credentials, cache behavior, referrer information, redirect policy, and streaming capabilities. Note that some features like persistent connections and max redirects have specific translations or are ignored. ```dart FetchClient({ this.mode = RequestMode.noCors, this.credentials = RequestCredentials.sameOrigin, this.cache = RequestCache.byDefault, this.referrer = '', this.referrerPolicy = RequestReferrerPolicy.strictOriginWhenCrossOrigin, this.redirectPolicy = RedirectPolicy.alwaysFollow, this.streamRequests = false, }); ``` -------------------------------- ### FetchResponse Methods Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchResponse-class Methods available for the FetchResponse class. ```APIDOC ## FetchResponse Methods ### Description Methods available for the FetchResponse class, including inherited methods. ### Methods - **noSuchMethod**(Invocation invocation) → dynamic - Inherited - Invoked when a nonexistent method or property is accessed. - **toString**() → String - Inherited - A string representation of this object. ``` -------------------------------- ### FetchClient Constructor Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient-class Creates a new HTTP client using the Fetch API. It allows configuration of request mode, credentials, cache, referrer, referrer policy, redirect policy, and whether to stream requests. Stream requests are only supported in Chromium 105+ browsers with HTTP/2 or HTTP/3 servers. ```dart FetchClient({ RequestMode mode = RequestMode.noCors, RequestCredentials credentials = RequestCredentials.sameOrigin, RequestCache cache = RequestCache.byDefault, String referrer = '', RequestReferrerPolicy referrerPolicy = RequestReferrerPolicy.strictOriginWhenCrossOrigin, RedirectPolicy redirectPolicy = RedirectPolicy.alwaysFollow, bool streamRequests = false, }) ``` -------------------------------- ### FetchRequest Constructor Implementation (Dart) Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchRequest/FetchRequest This code snippet shows the Dart implementation of the FetchRequest constructor. It initializes the request and sets up the abortTrigger, prioritizing an existing trigger from an Abortable request or combining it with a new trigger if provided. If the request is not Abortable, it simply uses the provided abortTrigger. ```dart FetchRequest(this.request, { Future? abortTrigger, }) : abortTrigger = switch(request) { Abortable(abortTrigger: final innerTrigger?) => abortTrigger == null ? innerTrigger : Future.any([ abortTrigger, innerTrigger, ]), _ => abortTrigger, }; ``` -------------------------------- ### FetchResponse Constructor Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchResponse/FetchResponse This section details the parameters required and optional for the FetchResponse constructor, used for creating cancelable streaming responses. ```APIDOC ## FetchResponse Constructor ### Description Creates a new cancelable streaming response. The `stream` should be a single-subscription stream. ### Method Constructor ### Endpoint N/A (Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Constructor Parameters - **stream** (Stream>) - Required - The stream of data for the response. - **statusCode** (int) - Required - The HTTP status code of the response. - **cancel** (CancelCallback) - Required - A callback function to cancel the response stream. - **url** (Uri) - Required - The URL the response was fetched from. - **redirected** (bool) - Required - Indicates if the response was a redirect. - **contentLength** (int?) - Optional - The content length of the response body. - **request** (BaseRequest?) - Optional - The original request that led to this response. - **headers** (Map) - Optional - A map of response headers. Defaults to an empty map. - **isRedirect** (bool) - Optional - Indicates if this response itself is a redirect. Defaults to false. - **persistentConnection** (bool) - Optional - Indicates if the connection should be kept persistent. Defaults to true. - **reasonPhrase** (String?) - Optional - The reason phrase for the status code. ### Request Example ```dart // Example usage (assuming necessary imports and definitions) final response = FetchResponse( stream, 200, cancel: () { /* cancel logic */ }, url: Uri.parse('http://example.com'), redirected: false, headers: {'Content-Type': 'application/json'} ); ``` ### Response #### Success Response (N/A for constructor) This is a constructor, not an endpoint that returns a response. #### Response Example N/A for constructor. ``` -------------------------------- ### FetchResponse Constructor (Dart) Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchResponse-class Initializes a new FetchResponse object. It requires a stream for the response body, status code, a cancellation callback, and the target URL. Optional parameters include content length, the originating request, headers, redirect status, persistent connection setting, and reason phrase. ```dart FetchResponse(Stream> stream, int statusCode, {required CancelCallback cancel, required Uri url, required bool redirected, int? contentLength, BaseRequest? request, Map headers = const {}, bool isRedirect = false, bool persistentConnection = true, String? reasonPhrase}) ``` -------------------------------- ### POST / Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/post Sends an HTTP POST request with the given headers and body to the specified URL. This method supports different types for the request body, including String, List, and Map. ```APIDOC ## POST / ### Description Sends an HTTP POST request with the given headers and body to the given URL. The `body` parameter can be a `String`, a `List`, or a `Map`. ### Method POST ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (Uri) - Required - The URL to send the POST request to. - **headers** (Map) - Optional - A map of HTTP headers to send with the request. - **body** (Object) - Optional - The body of the request. Can be a `String`, a `List`, or a `Map`. - If `String`, it's encoded using `encoding` and the content-type defaults to "text/plain". - If `List`, it's used as bytes for the request body. - If `Map`, it's encoded as form fields with content-type "application/x-www-form-urlencoded". - **encoding** (Encoding) - Optional - The encoding to use for the request body. Defaults to utf8. ### Request Example ```dart // Example with String body await http.post( Uri.parse('https://example.com/data'), body: 'This is the request body', ); // Example with Map body await http.post( Uri.parse('https://example.com/form'), body: { 'username': 'testuser', 'password': 'password123', }, ); ``` ### Response #### Success Response (200) - **Response** (Response) - An object representing the HTTP response from the server. #### Response Example ```json { "status": "success", "data": { "message": "Data received successfully" } } ``` ``` -------------------------------- ### FetchResponse Properties Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchResponse-class Details about the properties of the FetchResponse class. ```APIDOC ## FetchResponse Properties ### Description Properties of the FetchResponse class providing information about the response and cancellation capabilities. ### Properties - **cancel** (CancelCallback) - Required - Cancels current request and causes it to throw RequestCanceledException with provided reason. - **contentLength** (int?) - Optional - The size of the response body, in bytes. - **hashCode** (int) - Inherited - The hash code for this object. - **headers** (Map) - Inherited - The HTTP headers returned by the server. - **isRedirect** (bool) - Inherited - Indicates if the response is a redirect. - **persistentConnection** (bool) - Inherited - Whether the server requested that a persistent connection be maintained. - **reasonPhrase** (String?) - Inherited - The reason phrase associated with the status code. - **redirected** (bool) - Required - Whether the browser was redirected before loading the actual resource. - **request** (BaseRequest?) - Inherited - The (frozen) request that triggered this response. - **runtimeType** (Type) - Inherited - A representation of the runtime type of the object. - **statusCode** (int) - Inherited - The HTTP status code for this response. - **stream** (ByteStream) - Inherited - The stream from which the response body data can be read. - **url** (Uri) - Required - Target resource URL (the one after redirects, if there were any). ``` -------------------------------- ### Dart: Implement Fetch Request Sending Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchRequest/send This Dart code implements the 'send' method for making HTTP requests. It initializes a FetchClient, sends the request, and manages the response stream and client closure. Dependencies include the 'http' package for network operations. ```dart @override Future send() async { final client = FetchClient(); try { final response = await client.send(this); final stream = onDone(response.stream, client.close); return FetchResponse( stream, response.statusCode, cancel: response.cancel, url: response.url, redirected: response.redirected, request: response.request, headers: response.headers, isRedirect: response.isRedirect, persistentConnection: response.persistentConnection, reasonPhrase: response.reasonPhrase, contentLength: response.contentLength, ); } catch(_) { client.close(); rethrow; } } ``` -------------------------------- ### FetchResponse Operators Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchResponse-class Operators for the FetchResponse class. ```APIDOC ## FetchResponse Operators ### Description Operators available for the FetchResponse class. ### Operators - **operator ==**(Object other) → bool - Inherited - The equality operator. ``` -------------------------------- ### Dart HTTP Patch Method Implementation Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/patch Shows the implementation of the patch method, which internally calls the _sendUnstreamed helper method to handle the actual HTTP request. ```dart @override Future patch(Uri url, {Map? headers, Object? body, Encoding? encoding}) => _sendUnstreamed('PATCH', url, headers, body, encoding); ``` -------------------------------- ### FetchResponse Constructor Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchResponse-class Creates a new cancelable streaming response. ```APIDOC ## FetchResponse Constructor ### Description Creates a new cancelable streaming response with additional capabilities to cancel the request and access the final request URL. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart FetchResponse( stream, statusCode, cancel: cancelCallback, url: uri, redirected: true, contentLength: 1024, request: baseRequest, headers: {'Content-Type': 'application/json'}, isRedirect: false, persistentConnection: true, reasonPhrase: 'OK' ) ``` ### Response #### Success Response (200) This is a constructor, not an endpoint that returns a response. #### Response Example N/A ``` -------------------------------- ### FetchResponse Constructor Definition Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchResponse/FetchResponse Defines the constructor for the FetchResponse class, specifying its parameters for creating a cancelable streaming response. It includes a stream, status code, cancellation callback, URL, and other optional properties. ```dart FetchResponse( 1. Stream> stream, 2. int statusCode, { 3. required CancelCallback cancel, 4. required Uri url, 5. required bool redirected, 6. int? contentLength, 7. BaseRequest? request, 8. Map headers = const {}, 9. bool isRedirect = false, 10. bool persistentConnection = true, 11. String? reasonPhrase, }) ``` -------------------------------- ### HTTP Headers Property Implementation Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchResponse/headers Shows the implementation of the `headers` property, which is a map storing header names (converted to lowercase) and their corresponding values as strings. This is a core part of handling server responses. ```dart final Map headers; ``` -------------------------------- ### Implement toString for ClientException Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/RequestCanceledException/toString This implementation of the toString method provides a string representation for the ClientException class. It includes the exception message and the associated URI if available, which is useful for debugging and logging purposes. ```dart @override String toString() { if (uri != null) { return 'ClientException: $message, uri=$uri'; } else { return 'ClientException: $message'; } } ``` -------------------------------- ### Splitting HTTP Header Values Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchResponse/headers Demonstrates how to retrieve and split header values from a server response. It handles cases where multiple headers with the same name are returned, joining them with commas and whitespace, and then splitting them into a list. Dependencies include the `RegExp` class for pattern matching. ```dart final values = response.headers['fruit']!.split(RegExp(r'\s*,\s*')); ``` -------------------------------- ### Process Fetch Response Stream and Headers Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/send This Dart code processes an HTTP response stream, determines the expected body length based on the 'identity' encoding, and constructs a FetchResponse object. It handles potential null values for reader and encoding, and sets properties like status, headers, and content length. ```dart if (encoding == null || encoding.toLowerCase() == 'identity') { expectedBodyLength = contentLength; } else { expectedBodyLength = null; } } } else { contentLength = null; expectedBodyLength = null; } final stream = onDone( reader == null ? const Stream.empty() : _readAsStream( reader: reader, expectedLength: expectedBodyLength, uri: request.url, abortController: abortController, ), abort, ); return FetchResponse( stream, response.status, cancel: abort, url: Uri.parse(response.url), redirected: response.redirected, request: request, headers: { for (final (name, value) in response.headers.entries()) name: value, }, isRedirect: false, persistentConnection: false, reasonPhrase: response.statusText, contentLength: contentLength, ); } ``` -------------------------------- ### PATCH Method Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/patch Sends an HTTP PATCH request with the given headers and body to the given URL. The body can be a String, a List or a Map. ```APIDOC ## PATCH [URL] ### Description Sends an HTTP PATCH request with the given headers and body to the given URL. ### Method PATCH ### Endpoint [URL] ### Parameters #### Path Parameters - **url** (Uri) - Required - The URL to send the PATCH request to. #### Query Parameters - None #### Request Body - **body** (String | List | Map) - Optional - The body of the request. - **headers** (Map) - Optional - Request headers. - **encoding** (Encoding) - Optional - The encoding to use for the body. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **body** (dynamic) - The response body. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Dart Fetch Request Implementation Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/send Implements the `send` method for a custom fetch client in Dart. It handles different HTTP methods, serializes request bodies (including streaming), manages headers, and configures fetch options. It also integrates with AbortController for request cancellation and handles response status checks and potential redirect scenarios. ```dart @override Future send(BaseRequest request) async { if (_closed) { throw ClientException('Client is closed', request.url); } final requestMethod = request.method.toUpperCase(); final byteStream = request.finalize(); final RequestBody? body; final int bodySize; if (['GET', 'HEAD'].contains(requestMethod)) { body = null; bodySize = 0; } else if (streamRequests) { body = RequestBody.fromReadableStream( ReadableStream( ReadableStreamSource.fromStream( byteStream.transform( StreamTransformer.fromHandlers( handleData: (data, sink) => sink.add( (data is Uint8List ? data : Uint8List.fromList(data)).toJS, ), ), ), ), ), ); bodySize = -1; } else { final bytes = await byteStream.toBytes(); body = bytes.isEmpty ? null : RequestBody.fromJSTypedArray(bytes.toJS); bodySize = bytes.lengthInBytes; } final abortController = AbortController(); final fetchRequest = request is! FetchRequest ? null : request; final init = FetchOptions( body: body, method: request.method, redirect: ( request.followRedirects || (fetchRequest?.redirectPolicy ?? redirectPolicy) == RedirectPolicy.alwaysFollow ) ? RequestRedirect.follow : RequestRedirect.manual, headers: Headers.fromMap(request.headers), mode: fetchRequest?.mode ?? mode, credentials: fetchRequest?.credentials ?? credentials, cache: fetchRequest?.cache ?? cache, referrer: fetchRequest?.referrer ?? referrer, referrerPolicy: fetchRequest?.referrerPolicy ?? referrerPolicy, integrity: fetchRequest?.integrity ?? '', keepalive: bodySize < 63 * 1024 && !streamRequests && request.persistentConnection, signal: abortController.signal, duplex: !streamRequests ? null : RequestDuplex.half, ); ReadableStreamDefaultReader? reader; late final CancelCallback abort; abort = ([ reason, ]) { _abortCallbacks.remove(abort); // if stream is errored cancel rethrows error reason, // here we dont really care about it reader?.cancel().ignore(); abortController.abort(reason?.toJS); }; _abortCallbacks.add(abort); if (request case Abortable(:final abortTrigger?)) { // Tear-offs of external extension type interop members are disallowed // ignore: unnecessary_lambdas unawaited(abortTrigger.whenComplete(() => abort())); } final Response response; try { response = await _abortOnCloseSafeGuard( () => fetch(request.url.toString(), init), abortController, ); _throwIfAborted(abortController, request.url); if ( response.type == 'opaqueredirect' && !request.followRedirects && redirectPolicy != RedirectPolicy.alwaysFollow ) { return _probeRedirect( request: request, initialResponse: response, init: init, abortController: abortController, ); } } on RequestCanceledException { rethrow; } catch (e) { _throwIfAborted(abortController, request.url); throw ClientException('Failed to execute fetch: $e', request.url); } if (response.status == 0) { throw ClientException( 'Fetch response status code 0', request.url, ); } if (response.body == null && requestMethod != 'HEAD') { throw StateError('Invalid state: missing body with non-HEAD request.'); } reader = response.body?.getReader(); final int? contentLength; final int? expectedBodyLength; if (response.headers.get('Content-Length') case final value?) { contentLength = int.tryParse(value); if (contentLength == null || contentLength < 0) { throw ClientException('Content-Length header must be a positive integer value.', request.url); } // Although `identity` SHOULD NOT be used in the Content-Encoding // according to [RFC 2616](https://www.rfc-editor.org/rfc/rfc2616#section-3.5), // we'll handle this edge case anyway. final encoding = response.headers.get('Content-Encoding'); if (response.responseType == ResponseType.cors) { // For cors response we should ensure that we actually have access to // Content-Encoding header, otherwise response can be encoded but // we won't be able to detect it. final exposedHeaders = response.headers.get('Access-Control-Expose-Headers')?.toLowerCase(); if (exposedHeaders != null && ( exposedHeaders.contains('*') || exposedHeaders.contains('content-encoding') ) && ( encoding == null || encoding.toLowerCase() == 'identity' )) { expectedBodyLength = contentLength; } else { expectedBodyLength = null; } } else { // In non-cors response we have access to Content-Encoding header ``` -------------------------------- ### Dart HTTP POST Method Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/post This function sends an HTTP POST request to a specified URL. It supports custom headers, request bodies (String, List, or Map), and encoding. The encoding defaults to UTF-8. For advanced control, the 'send' method should be used. ```dart Future post( Uri url, { Map? headers, Object? body, Encoding? encoding, }) @override Future post(Uri url, {Map? headers, Object? body, Encoding? encoding}) => _sendUnstreamed('POST', url, headers, body, encoding); ``` -------------------------------- ### Implement Client Close Method Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/close This method closes the client, cleans up resources, and terminates active requests. It prevents further method calls after execution and handles cleanup callbacks. ```dart @override void close() { if (!_closed) { _closed = true; for (final abort in _abortCallbacks.toList()) { abort('Client closed'); } } } ``` -------------------------------- ### HTTP Request Sending with Send Method (Dart) Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/send The `send` method facilitates the transmission of HTTP requests asynchronously. It requires a `BaseRequest` object and returns a `Future`. Implementers must manage the request body stream using `BaseRequest.finalize` and handle potential `ClientException`s for HTTP errors. ```dart Future send( BaseRequest request ) ``` -------------------------------- ### FetchClient.send Method Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient-class Sends an HTTP request using the Fetch API and returns a Future that completes with the FetchResponse. This is the primary method for making requests with the FetchClient. It handles request details such as headers, body, and redirection policies. ```dart Future send(BaseRequest request) ``` -------------------------------- ### Dart HTTP Patch Method Signature Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/patch Defines the signature for the patch method in Dart's http package. It accepts a Uri, optional headers, body, and encoding to send an HTTP PATCH request. ```dart Future patch( Uri url, { Map? headers, Object? body, Encoding? encoding, } ) ``` -------------------------------- ### ByteStream finalize() Method Implementation Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchRequest/finalize This code snippet shows the implementation of the finalize method for the ByteStream class. It overrides the base method to call the finalize method on the associated request object, preparing the HTTP request for sending. ```dart @override ByteStream finalize() => request.finalize(); ``` -------------------------------- ### FetchRequest Class Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchRequest-class The FetchRequest class allows for overriding fetch options for a given request, providing fine-grained control over request behavior and caching. ```APIDOC ## Class: FetchRequest ### Description Wraps a request to provide fetch options overrides. This class allows for customization of various aspects of an HTTP request, including caching, redirects, headers, and more. ### Constructor #### FetchRequest(T request, {Future? abortTrigger}) * **request** (T) - Required - The base request to wrap. * **abortTrigger** (Future?, optional) - A future that, when completed, will abort the request. ### Properties #### `abortTrigger` → Future? Completion of this future aborts this request (if the client supports abortion). #### `cache` ↔ RequestCache? Controls how the request interacts with the browser's HTTP cache. #### `contentLength` ↔ int? The size of the request body, in bytes. #### `credentials` ↔ RequestCredentials? Defines what browsers do with credentials (cookies, HTTP authentication entries, and TLS client certificates). #### `finalized` → bool Indicates whether `finalize` has been called. #### `followRedirects` ↔ bool Determines whether the client should follow redirects. #### `headers` → Map The HTTP headers sent to the server. #### `integrity` ↔ String? The subresource integrity value of the request (e.g., `sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=`). #### `maxRedirects` ↔ int The maximum number of redirects to follow when `followRedirects` is true. #### `method` → String The HTTP method of the request. #### `mode` ↔ RequestMode? The mode of the request. #### `persistentConnection` ↔ bool Specifies whether a persistent connection should be maintained with the server. #### `redirectPolicy` ↔ RedirectPolicy? The redirect policy of the request, defining how client should handle `BaseRequest.followRedirects`. #### `referrer` ↔ String? The referrer of the request. Can be a same-origin URL, `about:client`, or an empty string. #### `referrerPolicy` ↔ RequestReferrerPolicy? The referrer policy of the request. #### `request` → T The inner request to be sent. #### `url` → Uri The URL to which the request will be sent. ### Methods #### `finalize()` → ByteStream Finalizes the HTTP request in preparation for it being sent. #### `send()` → Future Sends this request. #### `toString()` → String A string representation of this object. ``` -------------------------------- ### Dart HTTP PUT Method Implementation Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/put This code snippet shows the implementation of the `put` method in Dart, which is used to send an HTTP PUT request. It internally calls a private `_sendUnstreamed` method to handle the request. The method takes a URL, optional headers, body, and encoding as parameters. ```dart @override Future put(Uri url, {Map? headers, Object? body, Encoding? encoding}) => _sendUnstreamed('PUT', url, headers, body, encoding); ``` -------------------------------- ### DELETE Request Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/delete Sends an HTTP DELETE request with the given headers to the specified URL. Provides options for custom headers, request body, and encoding. ```APIDOC ## DELETE / ### Description Sends an HTTP DELETE request with the given headers to the given URL. ### Method DELETE ### Endpoint / ### Parameters #### Query Parameters - **url** (Uri) - Required - The URL to send the DELETE request to. - **headers** (Map) - Optional - Custom headers to include in the request. - **body** (Object) - Optional - The request body to send with the DELETE request. - **encoding** (Encoding) - Optional - The encoding for the request body. ### Request Example ```dart Future delete( Uri url, { Map? headers, Object? body, Encoding? encoding, }) ``` ### Response #### Success Response (200) - **Response** (Response) - The response from the server. #### Response Example ```dart // Example response structure (actual content depends on server) Response { statusCode: 200, headers: { ... }, body: "..." } ``` ``` -------------------------------- ### Dart HTTP DELETE Method Signature and Implementation Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient/delete Defines the signature for an HTTP DELETE request in Dart, including URL, headers, body, and encoding. The implementation shows how it delegates to a private `_sendUnstreamed` method for the actual request. ```dart @override Future delete( Uri url, { Map? headers, Object? body, Encoding? encoding, }) inherited Sends an HTTP DELETE request with the given headers to the given URL. For more fine-grained control over the request, use send instead. ## Implementation ```dart @override Future delete(Uri url, {Map? headers, Object? body, Encoding? encoding}) => _sendUnstreamed('DELETE', url, headers, body, encoding); ``` ``` -------------------------------- ### RequestCredentials Enum Values Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/RequestCredentials Defines the possible values for controlling credential handling in browser requests: same-origin, omit, and cors. ```dart const RequestCredentials('same-origin') const RequestCredentials('omit') const RequestCredentials('include') ``` -------------------------------- ### Dart toString Method Implementation Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/RequestCache/toString This snippet shows the implementation of the toString method in Dart. It overrides the default method to provide a custom string representation of an object, often used for debugging or logging purposes. The method returns the 'value' property of the object as its string representation. ```dart @override String toString() => value; ``` -------------------------------- ### RequestMode Enum Values (Dart) Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/RequestMode Defines the possible values for the RequestMode enum, each specifying a different behavior for cross-origin requests and response accessibility. Includes 'sameOrigin', 'noCors', 'cors', 'navigate', and 'webSocket'. ```dart const RequestMode('same-origin') const RequestMode('no-cors') const RequestMode('cors') const RequestMode('navigate') const RequestMode('websocket') ``` -------------------------------- ### Abort Trigger Property Implementation Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchRequest/abortTrigger This code snippet demonstrates the declaration of the 'abortTrigger' property, which is an optional Future that signals the abortion of a request. It is marked as final, indicating it should be assigned once. Its completion dictates how and when a request can be aborted during its lifecycle. ```dart @override final Future? abortTrigger; ``` -------------------------------- ### Set contentLength Property (Dart) Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchRequest/contentLength This snippet demonstrates the implementation for setting the contentLength property. It overrides the default setter to assign a value to the contentLength of the underlying request object. The value must be a non-negative integer or null. ```dart @override set contentLength(int? value) => request.contentLength = value; ``` -------------------------------- ### FetchClient.close Method Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchClient-class Closes the FetchClient and releases any associated resources. It's important to call this method when the client is no longer needed to prevent resource leaks. ```dart void close() ``` -------------------------------- ### RequestReferrerPolicy Enum Values (Dart) Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/RequestReferrerPolicy Defines the available referrer policies for web requests. Each value is a constant of type RequestReferrerPolicy, specifying how the 'Referer' header should be handled based on origin and security. The 'value' property provides the string representation for use in raw RequestInit. ```dart const RequestReferrerPolicy('strict-origin-when-cross-origin') const RequestReferrerPolicy('no-referrer') const RequestReferrerPolicy('no-referrer-when-downgrade') const RequestReferrerPolicy('same-origin') const RequestReferrerPolicy('origin') const RequestReferrerPolicy('strict-origin') const RequestReferrerPolicy('origin-when-cross-origin') const RequestReferrerPolicy('unsafe-url') ``` -------------------------------- ### Set maxRedirects Property (Dart) Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/FetchRequest/maxRedirects Sets the maximum number of redirects to follow. This value is used by the HttpClient to limit redirect chains. ```dart @override set maxRedirects(int value) => request.maxRedirects = value; ``` -------------------------------- ### RequestCache Enum Values Source: https://pub.dev/documentation/fetch_client/latest/fetch_client/RequestCache Demonstrates the declaration of different RequestCache enum values, each representing a distinct caching strategy for HTTP requests. These values control whether the browser uses, updates, or bypasses the cache. ```javascript const RequestCache('default') const RequestCache('no-store') const RequestCache('reload') const RequestCache('no-cache') const RequestCache('force-cache') const RequestCache('only-if-cached') ```