TL;DR: Stop Flutter UI jank in financial apps by moving heavy JSON parsing off the main thread.
asyncdoes not move work off the main isolate, andIsolate.run()pays a spawn cost on every call, so for high-frequency WebSocket feeds a long-lived background isolate connected withReceivePortandSendPortkeeps parsing off the UI thread and gives the frame budget back to rendering.
Key Takeaways
- Recognize that
async/awaitdoes not move execution off the main thread; synchronous operations likejsonDecode()will still block the Dart Event Loop. - A 60Hz display gives each frame about 16.7ms (about 8.3ms at 120Hz) for build, layout and paint combined, so any synchronous parse on the main isolate eats directly into that budget.
- Avoid
compute()orIsolate.run()for high-frequency WebSocket ticks, because each call spawns and tears down an isolate; measure that cost on your target devices with DevTools before deciding. - Architect a persistent, long-lived background Isolate that boots up once per session to handle continuous heavy data payloads without spawning costs.
- Use Dart's
ReceivePortandSendPortfor non-blocking message passing between the main UI thread and your background worker.
Your Flutter trading application connects to a live WebSocket feed. It receives thousands of order-book updates per second. Every time a burst of JSON data arrives, the scrolling stutters, button ripples freeze mid-animation, and the app feels momentarily unresponsive.
You’ve already wrapped your parsing logic in async and await, yet the UI jank persists. Users are noticing. In a trading app, a visible freeze while prices are moving erodes trust quickly.
The root of the problem lies in how Dart executes code. By default, your Dart code runs in a single isolate, the main isolate. Building widgets, handling gestures, and your JSON decoding all compete for time on its event loop. When jsonDecode() processes a large payload, it blocks that event loop until it finishes.
Optimizing the parsing code helps, but the larger win is moving the work off the main isolate. A persistent background isolate can take the heavy synchronous operations, leaving the main isolate free to hit its frame deadlines at 60 or 120Hz.
The Event Loop Bottleneck: Why async Doesn't Save You
A common misconception among intermediate Flutter developers is that marking a function as async pushes it to a background thread. It doesn't. Dart’s Event Loop simply schedules asynchronous tasks to run later on the exact same thread.
When you await a network request, the thread is free to render the UI. But the moment the data arrives and you begin parsing it synchronously, the thread is blocked.
// Anti-pattern: This blocks the main UI thread during heavy parsing
Future<void> handleWebSocketMessage(String rawJson) async {
// The event loop is blocked here!
// For a multi-megabyte payload this can take longer than a frame.
final dynamic decoded = jsonDecode(rawJson);
// The loop is STILL blocked here while instantiating objects
final List<OrderBookEntry> entries = (decoded as List)
.map((e) => OrderBookEntry.fromJson(e))
.toList();
_updateUI(entries);
}
Warning: Dart's
jsonDecodeis synchronous. If parsing plus the rest of the frame's work takes longer than about 16.7 milliseconds on a 60Hz display, you will miss a frame and cause visible UI stutter.
To fix this, we use additional Dart isolates: independent workers with their own memory heap and event loop that communicate with the main isolate only through message passing.
Moving Beyond compute() for High-Frequency Data
Flutter provides a helper function called compute(), which on native platforms is equivalent to Dart's Isolate.run() (on the web it runs on the current event loop instead). It spawns a background isolate, runs a function, returns the result, and shuts the isolate down.
For a one-off task like exporting a PDF, Isolate.run() is a good fit. For an app receiving hundreds of WebSocket messages a second, spawning an isolate per message wastes CPU on setup and teardown.
// The naive approach: Spawning an isolate per message
Future<void> processHighFrequencyData(String payload) async {
// Poor fit for high frequency: every call spawns and tears down
// an isolate before any parsing happens.
final result = await Isolate.run(() {
return parseOrderBook(payload);
});
_stateController.add(result);
}
Spawning an isolate is not free. It needs a new heap and event loop, and the Dart documentation notes that short-lived isolates carry overhead both for spawning and for copying objects between isolates, recommending long-lived isolates when the same computation runs repeatedly. Spawning one per WebSocket tick adds latency and CPU work to every message.
The alternative is a persistent worker isolate that stays alive for as long as the screen or session that needs it. If you are building a market-data or fintech app and want help profiling it, see our Flutter mobile app development services.
Architecting a Persistent Isolate Pool
To avoid the per-message spawning overhead, we need a dedicated background worker that boots up once and listens for continuous work.
This requires understanding two core Dart concepts:
- ReceivePort: A stream that listens for incoming messages.
- SendPort: The specific channel used to send messages to a
ReceivePort.
Let's build a JsonParsingService that initializes one long-lived isolate. Once one worker works, a pool is the same pattern repeated with round-robin dispatch.
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
class JsonParsingService {
Isolate? _isolate;
SendPort? _workerSendPort;
final ReceivePort _mainReceivePort = ReceivePort();
final Completer<void> _isReady = Completer<void>();
Future<void> initialize() async {
// 1. Spawn the isolate, passing the main thread's SendPort
_isolate = await Isolate.spawn(
_isolateRoutine, // Defined in the next section
_mainReceivePort.sendPort,
debugName: 'JsonParserWorker',
);
// 2. Listen to the main ReceivePort
_mainReceivePort.listen((message) {
if (message is SendPort) {
// The worker sends its SendPort as the first message
_workerSendPort = message;
_isReady.complete();
} else if (message is _IsolateResponse) {
// Handle completed parsing tasks
_handleWorkerResponse(message);
}
});
// Wait until the handshake is complete
await _isReady.future;
}
void _handleWorkerResponse(_IsolateResponse response) {
// We will implement the callback routing here
}
}
This establishes the foundation. The main thread boots up the isolate and waits for a "handshake": the isolate must hand over its own SendPort so the main thread knows where to route the heavy JSON payloads.
Handling Bi-Directional Communication
Isolates do not share mutable memory, so data moves between them only as messages. Isolates created with Isolate.spawn share code, which means you can send instances of your own classes, but objects with native resources and ReceivePorts cannot be sent.
We need a structured way to assign an ID to every task sent to the worker. This ensures that when the worker sends the parsed data back, we know exactly which future to complete on the main thread.
// Data classes for safe message passing
class _IsolateRequest {
final int id;
final String jsonPayload;
_IsolateRequest(this.id, this.jsonPayload);
}
class _IsolateResponse {
final int id;
final dynamic parsedData;
final String? error;
_IsolateResponse(this.id, this.parsedData, {this.error});
}
// The isolated entry point (Must be a top-level or static function)
void _isolateRoutine(SendPort mainSendPort) {
// 1. Create the worker's own ReceivePort
final workerReceivePort = ReceivePort();
// 2. Complete the handshake by sending the worker's SendPort to main
mainSendPort.send(workerReceivePort.sendPort);
// 3. Listen for incoming JSON payloads
workerReceivePort.listen((message) {
if (message is _IsolateRequest) {
try {
// CPU-Intensive Work happens here, safely off the main thread
final decoded = jsonDecode(message.jsonPayload);
// Send success back
mainSendPort.send(_IsolateResponse(message.id, decoded));
} catch (e) {
// Send error back
mainSendPort.send(_IsolateResponse(message.id, null, error: e.toString()));
}
}
});
}
Tip: According to the
SendPort.senddocumentation, immutable objects such as strings are shared rather than copied, so sending the raw JSON string to the worker is cheap. Mutable objects such as the decodedMapandListare copied, which can cost linear time in the size of the object graph. Send back only the fields the UI needs, or build compact typed objects in the worker, to keep that copy small. OnlyIsolate.exithands a result over without copying, which suits one-shot workers rather than long-lived ones.
Creating the Public API for the Main Thread
Now we need to wire up the JsonParsingService so the rest of your app can simply call an async function and get the parsed result, completely unaware of the complex isolate routing happening underneath.
We'll use a Map<int, Completer> to track pending tasks.
class JsonParsingService {
// ... previous initialization code ...
int _taskIdCounter = 0;
final Map<int, Completer<dynamic>> _pendingTasks = {};
Future<dynamic> parseJsonOffThread(String rawJson) async {
await _isReady.future; // Ensure isolate is booted
final taskId = _taskIdCounter++;
final completer = Completer<dynamic>();
_pendingTasks[taskId] = completer;
// Dispatch work to the background isolate
_workerSendPort?.send(_IsolateRequest(taskId, rawJson));
return completer.future;
}
void _handleWorkerResponse(_IsolateResponse response) {
final completer = _pendingTasks.remove(response.id);
if (completer == null) return;
if (response.error != null) {
completer.completeError(Exception(response.error));
} else {
completer.complete(response.parsedData);
}
}
}
With this architecture, your UI code awaits the parseJsonOffThread method. The decoding runs in the background isolate, and the main isolate only pays for receiving the result.
Integrating with a Live WebSocket Stream
Let's look at how this impacts the actual data layer of a financial application. Instead of blocking the UI on every tick, the stream listener delegates the processing.
class MarketDataRepository {
final WebSocketChannel _channel;
final JsonParsingService _parser;
final StreamController<List<OrderBookEntry>> _orderBookStream = StreamController.broadcast();
MarketDataRepository(this._channel, this._parser) {
_channel.stream.listen(_onDataReceived);
}
Stream<List<OrderBookEntry>> get orderBook => _orderBookStream.stream;
Future<void> _onDataReceived(dynamic rawData) async {
if (rawData is! String) return;
try {
// 1. The raw string is shared with the worker, not copied
// 2. JSON decoding happens on the worker isolate
// 3. The decoded result is copied back to the main isolate
final dynamic decodedMap = await _parser.parseJsonOffThread(rawData);
// Note: Map -> Object conversion can also be moved to the isolate
// if it becomes a bottleneck, but jsonDecode is usually the primary culprit.
final entries = (decodedMap['bids'] as List)
.map((e) => OrderBookEntry.fromJson(e))
.toList();
_orderBookStream.add(entries);
} catch (e) {
debugPrint('Failed to parse market data: $e');
}
}
}
Production Note: If your
OrderBookEntry.fromJson()instantiation is highly complex and involves heavy date parsing or cryptographic verification, you should move that mapping logic directly into the_isolateRoutineas well. Objects sent through theSendPortmust not hold native resources or ports.
Managing Isolate Lifecycles and Memory Trade-offs
Isolates are not free. Each one has its own heap, so isolates left running after their screen is gone keep holding memory and can push a constrained device toward being killed by the OS.
When your application no longer needs the parsing service (for instance, when the user logs out or closes the trading view), tear down the ports and kill the isolate.
class JsonParsingService {
// ... previous code ...
void dispose() {
// 1. Cancel all pending futures to prevent UI deadlocks
for (final completer in _pendingTasks.values) {
if (!completer.isCompleted) {
completer.completeError(Exception("Service disposed"));
}
}
_pendingTasks.clear();
// 2. Close the main receive port
_mainReceivePort.close();
// 3. Kill the background isolate so its heap can be released
_isolate?.kill(priority: Isolate.immediate);
_isolate = null;
_workerSendPort = null;
}
}
Isolate.immediate asks the isolate to terminate as soon as possible instead of after its pending events, after which the VM can reclaim its heap.
A persistent isolate removes the overhead of repeated isolate creation and keeps heavy synchronous work out of your Flutter UI layer. Verify the result with the DevTools Performance view on a low-end device: frame build times should stay under budget while the feed is busy. If a single worker becomes the bottleneck, add more workers, or throttle the feed so the UI only renders the latest snapshot per frame.
Sources
- Dart documentation: Concurrency and isolates (short-lived vs long-lived isolates,
ReceivePorthandshake) - Dart API: SendPort.send (what can be sent, which objects are shared and which are copied)
- Flutter API: compute (equivalence with
Isolate.run, web behavior)
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
Why does async code still freeze a Flutter UI?
async only lets code wait without blocking; the work itself still runs on the main isolate. CPU-heavy tasks such as parsing large JSON payloads block frame rendering, which causes jank.
When is compute() not enough?
compute() starts a new isolate for every call. For high-frequency work, such as parsing every message from a live market-data stream, that startup cost adds up, so a long-lived isolate or a pool of isolates performs better.
How do isolates communicate with the main thread?
Isolates do not share memory. They exchange messages through SendPort and ReceivePort, so design a small request and response protocol and send only the data the UI actually needs.
Do background isolates increase memory use?
Yes. Each isolate has its own heap, so a pool of isolates uses more memory than one. Size the pool to the number of CPU cores you need and shut isolates down when the screen that uses them closes.
