By Updated •7 min read

Dart Event Loop: Microtasks, Futures, and Flutter Isolates

DartFlutterAsyncConcurrencyEvent Loop
Dart Event Loop illustrated showing Microtask Queue and Event Queue flow

Introduction

The Dart event loop runs one callback at a time within an isolate. Microtasks run before the next queued event; await allows other work to proceed while a future is pending. Neither async nor Future(() => work()) moves CPU-heavy work onto another isolate.

This guide is for Flutter developers debugging execution order or a UI that pauses during data processing. The standalone examples were checked with Dart 3.13.2 on macOS. They demonstrate ordering and result correctness, not a device-performance benchmark. Dart's concurrency overview explains the underlying isolate model.

One isolate runs Dart callbacks sequentially

A Flutter app normally starts its UI code in the main isolate. Each isolate has its own event loop and memory. Separate isolates can execute concurrently, including on different processor cores; Flutter's engine and platform integrations also do work outside your Dart UI callbacks.

Calling Dart universally single-threaded hides that distinction. Within one isolate, a long synchronous callback prevents that isolate from handling the next event. Across isolates, Dart can perform parallel work.

Dart event loop and the priority of microtasks over queued events

Once the current synchronous work finishes, pending microtasks drain before the next queued event runs. After that event, newly scheduled microtasks run before another event is selected. An empty queue does not necessarily end a Flutter app: the runtime can wait for more events while timers, ports, or other resources keep it alive.

Microtasks and events: what belongs where?

OperationScheduling behaviorPractical implication
A normal function callRuns immediately on the current stackLong work blocks this isolate
scheduleMicrotask or Future.microtaskSchedules a microtaskRuns before the next timer/event callback
Future(() => work())Schedules work through the event queueDefers work, but still uses the same isolate
Future.delayed(Duration.zero, work)Schedules a timer callbackZero delay is not immediate execution
future.then(callback)Depends on future completion and registrationDo not assume every listener adds a separate event
Isolate.run(work)Runs sendable work in another isolateUseful for sufficiently expensive CPU work on supported native platforms

The scheduleMicrotask API guarantees ordering between its callbacks and warns about starving timer events. The Future API describes its constructors and completion behavior. A future represents a result; it does not identify a background thread.

A runnable execution-order example

Save this as event_order.dart and run dart run event_order.dart:

import 'dart:async';

void main() {
  print('sync: start');

  Future<void>.delayed(Duration.zero, () => print('event: timer'));
  scheduleMicrotask(() => print('microtask: first'));
  Future<void>.microtask(() => print('microtask: second'));
  Future<String>.value('ready').then((_) => print('future: listener'));

  print('sync: end');
}

Expected output:

sync: start
sync: end
microtask: first
microtask: second
future: listener
event: timer

The listener on the already completed future does not jump ahead of the microtasks registered earlier in this example. Both synchronous prints finish first. The pending microtasks and future listener execute before the zero-duration timer.

Do not extrapolate this exact output to futures whose completion depends on different network requests. Their arrival order is not established by the order in which you started them.

What async and await actually change

An async function runs its initial synchronous work when called. At an await, it suspends that function's continuation while the caller and event loop can proceed.

Future<String> loadName() async {
  print('load: before await');
  await Future<void>.delayed(Duration.zero);
  print('load: after await');
  return 'Moeen';
}

Future<void> main() async {
  final pending = loadName();
  print('main: still running');
  print(await pending);
}

Output:

load: before await
main: still running
load: after await
Moeen

A network request often spends much of its time waiting outside the Dart callback. An expensive JSON conversion after the response arrives still consumes time in the isolate that executes it. Marking that conversion function async does not remove the work.

Why wrapping CPU work in a future can still cause jank

This function defers its calculation but runs it on the calling isolate:

Future<int> sumLater(List<int> values) {
  return Future<int>(() => values.fold(0, (total, value) => total + value));
}

The UI may get an opportunity to handle an event before the calculation starts. Once the calculation begins, it runs synchronously until completion. For a small list that is fine. For work that exceeds your measured frame budget, consider another isolate.

For a native Dart or Flutter target:

import 'dart:isolate';

Future<int> sumInWorker(List<int> values) {
  return Isolate.run(() => values.fold<int>(0, (total, value) => total + value));
}

Future<void> main() async {
  final result = await sumInWorker([1, 2, 3, 4]);
  if (result != 10) throw StateError('Unexpected sum: $result');
  print(result);
}

This verifies the calculation, not a speed improvement. Starting an isolate, transferring data, and allocating results have costs. Profile representative payloads on a target device before deciding the boundary. Keep widget state in the UI isolate and return data from workers. See Dart isolates for sendability constraints and Flutter concurrency guidance for platform limitations.

On Flutter web, compute executes on the current event loop; it does not create the native-isolate parallelism that this example uses. A large calculation may need a separate web-worker design.

Avoid event starvation and lifecycle bugs

Do not recursively schedule endless microtasks

A callback that repeatedly schedules another microtask can prevent timers and input from being handled. Microtasks are for short scheduling work, not a general background processing loop. Use a bounded batch or a worker for substantial computation.

Streams are not one universal queue rule

A stream delivers multiple values, but a synchronous stream controller can deliver events during the call that adds them. Async generators and asynchronous controllers have different delivery behavior. Check the stream's contract rather than assuming every stream event is a separate timer-like event.

Handle failures and stale UI updates

Waiting for a future does not guarantee its result is still relevant when it completes. A search response may arrive after a newer query, or a widget may have been disposed. Handle errors, check lifecycle state, and use a request identifier or cancellation mechanism where needed. Our Flutter testing guide covers how to exercise application behavior beyond a successful request.

Keep work out of build

A widget's build method must return a widget synchronously. Create long-lived futures outside build, then use an appropriate state holder or FutureBuilder. Otherwise, a rebuild can start the same request repeatedly. The Flutter architecture guide explains where data access and presentation state belong.

A practical debugging checklist

SymptomInspect firstCheck before changing architecture
UI freezes after an API responseParsing and transformations on the UI isolateProfile actual payload sizes in profile mode
Timer runs later than expectedLong synchronous callbacks and microtask chainsRemove unbounded scheduling loops
Old search results overwrite new onesRequest completion orderAdd stale-result protection
Worker makes a small task slowerStartup, allocation, and message overheadCompare the whole operation, not just its inner loop
Web behavior differs from nativePlatform-specific concurrency behaviorTest the target platform explicitly

For background persistence and API retries, continue with offline-first Flutter synchronization. Those are state-consistency problems as well as scheduling problems.

Conclusion

The event loop explains callback ordering within an isolate. It does not turn asynchronous syntax into parallel CPU execution.

  • Finish synchronous work before expecting queued callbacks to run.
  • Keep microtasks short and bounded.
  • Treat a future as a pending result, not a worker thread.
  • Move CPU work only after profiling shows that the transfer and startup costs are justified.
  • Test execution order separately from device-performance claims.

Preparing for a Dart interview? These Dart interview questions cover isolates, Futures, Streams and more.

If your Flutter app pauses during parsing, synchronization, or large UI updates, book a project discussion to review the bottleneck and choose a measurable fix.

Share

See the project work

Explore the decisions, scope, and validation behind selected mobile and AI projects.

Explore case studies