Sub topic 12
Parsing Large Responses in a Background Isolate
This chapter assumes you know Dart classes, Future, async and await, Flutter widget lifecycles, and how to add packages to pubspec.yaml. It focuses on keeping JSON parsing from blocking Flutter’s UI.
Why large JSON responses cause jank
Flutter normally runs your widget code, painting, input handling, and synchronous Dart code on the UI isolate. An isolate is an independent Dart execution context with its own memory. A long-running operation on the UI isolate can delay frames and make scrolling or tapping feel slow.
An HTTP request is asynchronous, so waiting for the network usually does not block the UI. However, jsonDecode is synchronous. If the response contains thousands of records, converting its text into Dart objects can take long enough to cause dropped frames.
Flutter’s compute function runs a top-level or static function away from the UI isolate on platforms that support isolates. Pass it simple, sendable data such as a String, List, or Map. Do not pass a BuildContext, widget, or open client connection.
Parse the response in `compute`
The parsing function must be available at the top level. It receives the response body and returns typed model objects. The HTTP request itself remains outside the isolate.
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
class Post {
const Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'] as int,
title: json['title'] as String,
);
}
final int id;
final String title;
}
// This function runs in the parsing isolate.
List<Post> parsePosts(String body) {
final decoded = jsonDecode(body) as List<dynamic>;
return decoded
.map((item) => Post.fromJson(item as Map<String, dynamic>))
.toList();
}
Future<List<Post>> fetchPosts(http.Client client) async {
final uri = Uri.https(
'jsonplaceholder.typicode.com',
'/posts',
);
final response = await client.get(uri);
if (response.statusCode != 200) {
throw Exception('Request failed: ${response.statusCode}');
}
return compute(parsePosts, response.body);
}compute serializes the message, starts or uses a worker isolate, calls parsePosts, and returns the result as a Future. The UI isolate can continue processing frames while parsing occurs.
Decide when an isolate is worthwhile
Starting an isolate has overhead. For a small response, moving the work may take longer than parsing it directly. Measure the real application before adding complexity.
| Response or operation | Usual choice |
|---|---|
| Small JSON response | Parse directly with `jsonDecode` |
| Large list of complex objects | Consider `compute` |
| Repeated expensive transformations | Use an isolate or dedicated worker |
| Network request itself | Keep it asynchronous on the main isolate |
An isolate does not make a slow server faster. It only moves CPU work, such as decoding and transforming data. You should also validate the decoded shape, because malformed JSON or an unexpected API response still produces an exception.
Platform and lifecycle considerations
On native Flutter platforms, compute uses another isolate. Flutter web has different execution constraints, so large parsing tasks may not receive the same parallelism. Test performance on every target platform you support.
If a widget starts fetchPosts, check that it is still mounted before calling setState after the future completes. A background isolate cannot update a widget directly.
Exercise
Why should response.body be passed to compute instead of passing an http.Client or BuildContext?
Show answer
A response body is sendable data, while an HTTP client and BuildContext contain state tied to the original isolate and should not be used by the parsing isolate.