CancelToken class

A token that can be attached to a RestRequest to allow the caller to cancel an in-flight HTTP request.

(new): the first-class answer to "user navigated away mid-request, the result is useless now, stop the network call". Before 8.2 the only way to "cancel" was to ignore the returned Future — but the underlying socket stayed open, the response body was still read (wasting CPU + memory + bandwidth), and the server kept running whatever the request asked for.

Usage

final token = CancelToken;
unawaited(httpClient.execute(
request,
decoder: jsonDecoder,
cancelToken: token,
));
// ...later, the user navigates away:
token.cancel('user navigated away');

Throwing away the Future (the typical "abandon this call" pattern) is no longer enough. Always pass a CancelToken for any long-running request the user might want to abort.

Constructors

CancelToken()

Properties

hashCode int
The hash code for this object.
no setterinherited
isCancelled bool
true after cancel has been called. Once true, the token cannot be reset.
no setter
reason String?
The reason string passed to cancel (or 'cancelled' if cancel was called without an argument). null until cancel is called.
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

cancel([String reason = 'cancelled']) → void
Cancels any HttpClient.execute call that has this token attached. Idempotent (second call is a no-op). The reason is surfaced via RequestCancelledException.reason.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
onCancel(void cb(String reason)?) → void
(internal): register the cancel callback. Called by HttpPackageClient immediately before http.Client.send. The callback receives the cancel reason and is expected to abort the in-flight socket.
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited