CancellationToken class
A token that can be used to cancel asynchronous operations.
Pass a CancellationToken to search operations to allow cancelling long-running searches when the user types a new query or navigates away.
Example:
class MySearchProvider extends SearchProvider {
CancellationToken? _activeToken;
@override
Future<SearchResult> search(
String query, {
int page = 1,
int pageSize = 10,
CancellationToken? cancellationToken,
}) async {
// Cancel previous search
_activeToken?.cancel();
_activeToken = cancellationToken ?? CancellationToken();
try {
final response = await http.get(buildUrl(query));
// Check if cancelled before processing
if (_activeToken!.isCancelled) {
throw CancelledException();
}
return parseResponse(response);
} catch (e) {
if (_activeToken?.isCancelled ?? false) {
return SearchResult.empty(query);
}
rethrow;
}
}
}
Constructors
- CancellationToken.new()
- Creates a new cancellation token.
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- isCancelled → bool
-
Whether this token has been cancelled.
no setter
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
cancel(
) → void - Cancels this token and notifies all listeners.
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
onCancelled(
void callback()) → void Function() - Registers a callback to be called when this token is cancelled.
-
throwIfCancelled(
) → void - Throws CancelledException if this token has been cancelled.
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited