CancellationToken class

A token for controlling the cancellation of Cancellable operations.

A single token can be used for multiple Cancellable operations.

Example implementation

CancellationToken cancellationToken = CancellationToken();

@override
void initState() {
  super.initState();
  loadData();
}

@override
void dispose() {
  cancellationToken.cancel();
  super.dispose();
}

Future<void> loadData() async {
  loading = false;
  try {
    someDataA = await getDataA(cancellationToken: cancellationToken);
    someDataB = await getDataB(cancellationToken: cancellationToken);
    setState(() {});
  } on CancelledException {
    // Ignore cancellations
  } catch (e, stackTrace) {
    error = true;
  }
}

See also:

Constructors

CancellationToken()

Properties

exception Exception?
The exception given when the token was cancelled.
no setter
hasCancellables bool
Whether or not the token has any attached cancellables.
no setter
hashCode int
The hash code for this object.
no setterinherited
isCancelled bool
Whether or not the token has been cancelled.
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

attachCancellable(Cancellable cancellable) → void
Attaches a Cancellable to this token.
cancel([Exception? exception]) → void
Cancels all operations using this token.
cancelWithReason(String? cancellationReason) → void
A convenience method for cancelling the token with a CancelledException that includes the reason for cancellation.
detachCancellable(Cancellable cancellable) → void
Detaches a Cancellable from this token.
merge(CancellationToken other) → MergedCancellationToken
Merges this CancellationToken with another to create a single token that will be cancelled when either token is cancelled.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
throwIfCancelled() → void
Throws the cancellation exception if the token has already been cancelled.
toString() String
A string representation of this object.
inherited

Operators

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