Appearance
dart:async
Support for asynchronous programming, with classes such as Future and Stream.
Futures and Streams are the fundamental building blocks of asynchronous programming in Dart. They are supported directly in the language through async and async* functions, and are available to all libraries through the dart:core library.
This library provides further tools for creating, consuming and transforming futures and streams, as well as direct access to other asynchronous primitives like Timer, scheduleMicrotask and Zone.
To use this library in your code:
dart
import 'dart:async';Future
A Future object represents a computation whose return value might not yet be available. The Future returns the value of the computation when it completes at some time in the future. Futures are often used for APIs that are implemented using a different thread or isolate (e.g., the asynchronous I/O operations of dart:io or HTTP requests of dart:html).
Many methods in the Dart libraries return Futures when performing tasks. For example, when binding an HttpServer to a host and port, the bind() method returns a Future.
dart
HttpServer.bind('127.0.0.1', 4444)
.then((server) => print('${server.isBroadcast}'))
.catchError(print);Future.then registers a callback function that runs when the Future's operation, in this case the bind() method, completes successfully. The value returned by the operation is passed into the callback function. In this example, the bind() method returns the HttpServer object. The callback function prints one of its properties. Future.catchError registers a callback function that runs if an error occurs within the Future.
Stream
A Stream provides an asynchronous sequence of data. Examples of data sequences include individual events, like mouse clicks, or sequential chunks of larger data, like multiple byte lists with the contents of a file such as mouse clicks, and a stream of byte lists read from a file. The following example opens a file for reading. Stream.listen registers callback functions that run each time more data is available, an error has occurred, or the stream has finished. Further functionality is provided on Stream, implemented by calling Stream.listen to get the actual data.
dart
Stream<List<int>> stream = File('quotes.txt').openRead();
stream.transform(utf8.decoder).forEach(print);This stream emits a sequence of lists of bytes. The program must then handle those lists of bytes in some way. Here, the code uses a UTF-8 decoder (provided in the dart:convert library) to convert the sequence of bytes into a sequence of Dart strings.
Another common use of streams is for user-generated events in a web app: The following code listens for mouse clicks on a button.
dart
querySelector('#myButton')!.onClick.forEach((_) => print('Click.'));Other resources
The dart:async section of the library tour: A brief overview of asynchronous programming.
Use Future-Based APIs: A closer look at Futures and how to use them to write asynchronous Dart code.
Futures and Error Handling: Everything you wanted to know about handling errors and exceptions when working with Futures (but were afraid to ask).
The Event Loop and Dart: Learn how Dart handles the event queue and microtask queue, so you can write better asynchronous code with fewer surprises.
test package: Asynchronous Tests: How to test asynchronous code.
Classes
| Class | Description |
|---|---|
| Completer<T> | A way to produce Future objects and to complete them later with a value or error. |
| EventSink<T> | A Sink that supports adding errors. |
| Future<T> | The result of an asynchronous computation. |
| FutureOr<T> | A type representing values that are either Future<T> or T. |
| MultiStreamController<T> | An enhanced stream controller provided by Stream.multi. |
| Stream<T> | A source of asynchronous data events. |
| StreamConsumer<S> | Abstract interface for a "sink" accepting multiple entire streams. |
| StreamController<T> | A controller with the stream it controls. |
| StreamIterator<T> | An Iterator-like interface for the values of a Stream. |
| StreamSink<S> | A object that accepts stream events both synchronously and asynchronously. |
| StreamSubscription<T> | A subscription on events from a Stream. |
| StreamTransformer<S, T> | Transforms a Stream. |
| StreamTransformerBase<S, T> | Base class for implementing StreamTransformer. |
| StreamView<T> | Stream wrapper that only exposes the Stream interface. |
| SynchronousStreamController<T> | A stream controller that delivers its events synchronously. |
| Timer | A countdown timer that can be configured to fire once or repeatedly. |
| Zone | A zone represents an environment that remains stable across asynchronous calls. |
| ZoneDelegate | An adapted view of the parent zone. |
| ZoneSpecification | A parameter object with custom zone function handlers for Zone.fork. |
Exceptions
| Exception | Description |
|---|---|
| AsyncError | An error and a stack trace. |
| DeferredLoadException | Thrown when a deferred library fails to load. |
| ParallelWaitError<V, E> | Error thrown when waiting for multiple futures, when some have errors. |
| TimeoutException | Thrown when a scheduled timeout happens while waiting for an async result. |
Extensions
| Extension | on | Description |
|---|---|---|
| FutureExtensions<T> | Future<T> | Convenience methods on futures. |
| FutureIterable<T> | Iterable<Future<T>> | |
| FutureRecord2<T1, T2> | Record | Parallel operations on a record of futures. |
| FutureRecord3<T1, T2, T3> | Record | Parallel operations on a record of futures. |
| FutureRecord4<T1, T2, T3, T4> | Record | Parallel operations on a record of futures. |
| FutureRecord5<T1, T2, T3, T4, T5> | Record | Parallel operations on a record of futures. |
| FutureRecord6<T1, T2, T3, T4, T5, T6> | Record | Parallel operations on a record of futures. |
| FutureRecord7<T1, T2, T3, T4, T5, T6, T7> | Record | Parallel operations on a record of futures. |
| FutureRecord8<T1, T2, T3, T4, T5, T6, T7, T8> | Record | Parallel operations on a record of futures. |
| FutureRecord9<T1, T2, T3, T4, T5, T6, T7, T8, T9> | Record | Parallel operations on a record of futures. |
Functions
| Function | Description |
|---|---|
| runZoned<R> | Runs body in its own zone. |
| runZonedGuarded<R> | Runs body in its own error zone. |
| scheduleMicrotask | Runs a function asynchronously. |
| unawaited | Explicitly ignores a future. |
Typedefs
| Typedef | Description |
|---|---|
| ControllerCallback | Type of a stream controller's onListen, onPause and onResume callbacks. |
| ControllerCancelCallback | Type of stream controller onCancel callbacks. |
| CreatePeriodicTimerHandler | The type of a custom Zone.createPeriodicTimer implementation function. |
| CreateTimerHandler | The type of a custom Zone.createTimer implementation function. |
| ErrorCallbackHandler | The type of a custom Zone.errorCallback implementation function. |
| ForkHandler | The type of a custom Zone.fork implementation function. |
| HandleUncaughtErrorHandler | The type of a custom Zone.handleUncaughtError implementation function. |
| PrintHandler | The type of a custom Zone.print implementation function. |
| RegisterBinaryCallbackHandler | The type of a custom Zone.registerBinaryCallback implementation function. |
| RegisterCallbackHandler | The type of a custom Zone.registerCallback implementation function. |
| RegisterUnaryCallbackHandler | The type of a custom Zone.registerUnaryCallback implementation function. |
| RunBinaryHandler | The type of a custom Zone.runBinary implementation function. |
| RunHandler | The type of a custom Zone.run implementation function. |
| RunUnaryHandler | The type of a custom Zone.runUnary implementation function. |
| ScheduleMicrotaskHandler | The type of a custom Zone.scheduleMicrotask implementation function. |
| ZoneBinaryCallback<R, T1, T2> | A two-argument function, like the argument to Zone.runBinary. |
| ZoneCallback<R> | A no-argument function, like the argument to Zone.run. |
| ZoneUnaryCallback<R, T> | A one-argument function, like the argument to Zone.runUnary. |