NetworkingMedium30 XP3 min read
How do you decode large JSON payloads without blocking the UI?
TL;DR: Use compute(jsonDecode, rawString) to run JSON decoding in a background Isolate. compute() is a convenience wrapper around Isolate.run() that handles serialization of the return value. Use for payloads larger than ~100KB.
Full Answer
Dart is single-threaded per Isolate. jsonDecode() on a 1MB JSON string can block the UI for 100-200ms, causing visible jank. Moving it to a background Isolate keeps the main isolate free.
- ▸compute(fn, arg): Spawns an Isolate, runs fn(arg), returns result — simplest option
- ▸Isolate.run(() => ...): More control, can do multiple operations
- ▸When to use: JSON > 100KB, complex parsing (nested objects, lists of 500+ items)
- ▸When to skip: Small responses (<50KB) — Isolate spawn overhead (~5ms) outweighs the benefit
Code Examples
dartBackground JSON parsing with compute()
Output
// Main isolate: makes HTTP request, awaits compute result // Background isolate: runs _parseQuestions, returns typed list // No UI jank even for 500KB responses
Common Mistakes
- ✗Passing a closure to compute() — closures capture context from the current isolate and can't be sent
- ✗Using ResponseType.json with Dio — Dio's JSON transformer already runs on the main isolate; use plain text + compute instead
Interview Tip
💡
Show the top-level function requirement for compute(). The reason: Isolates share no memory, so the function must be serializable by reference (a pointer to a top-level function).
#isolate#compute#json-decode#performance#background