What do you know about asynchronous programming in Dart?
sobes.tech AI
Answer from AI
Asynchronous programming in Dart is implemented using:
-
Isolates: Independent workers, each with its own memory. Used for parallel execution of resource-intensive tasks without blocking the main user interface thread. Communication between isolates occurs via ports (ReceivePort, SendPort).
-
Keywords
async,await:asyncmarks a function that performs asynchronous operations and returns aFuture.awaitis used inside anasyncfunction to wait for the completion of aFuture. Whenawaitis reached, the function's execution is paused, allowing other operations to run until theFuturecompletes with a value or an error.
Future<String> fetchData() async { // Simulate delay await Future.delayed(Duration(seconds: 2)); return 'Data received'; } void main() async { print('Start'); String result = await fetchData(); // Wait for fetchData to complete print(result); print('End'); } -
Future<T>class: Represents the result of an asynchronous operation that will be available in the future. AFuturecan be in one of three states:- Uncompleted
- Completed with a value
- Completed with an error
Completion of a
Futureis handled withthen(),catchError(),whenComplete(), orawait. -
Stream<T>class: Represents a sequence of asynchronous events. Used for processing data streams, such as reading from a file, receiving data over a network, or user interface events. A stream can be single-subscription or broadcast. Event handling is done vialisten(),async*,yield.Stream<int> countStream(int to) async* { for (int i = 1; i <= to; i++) { await Future.delayed(Duration(seconds: 1)); yield i; // Send value to stream } } void main() { Stream<int> stream = countStream(3); stream.listen( (data) => print('Received: $data'), onError: (error) => print('Error: $error'), onDone: () => print('Stream finished'), ); }
Asynchronous programming in Dart is based on the "single event loop" model. The main thread executes code sequentially, but when it encounters an asynchronous operation (e.g., await or Future.then), it hands it over to the "event queue" and continues executing the next code. When the asynchronous operation completes, its result is sent back to the "event queue." The event loop constantly checks the "event queue" and executes tasks when the main thread is free.