UI Jank while parsing json
Solving UI Janks While Parsing Json There is no direct support for json in dart, (as name significies Javascript on it), have to convert it to map and then to object, large object parsing cause much load in the main thread, which janks or freeze the ui just to parse.
- It disrupts the user experience, as user may think app hanged and close.
! Also this can be done when there is heavy logic processing not only for json parsing, it’s just one of use case
How to solve this? For this we use, something called Isolates in flutter. Isolates are lightweight thread, where we can put the raw json and it does heavy lift JSON parsing to model for us.
Example 1: Using Isolate.run for custom parsing
Isolate.run is a newer, simpler API for running code in an isolate and getting results back.
dart
import 'dart:convert';import 'dart:isolate';
// Simple modelclass User { final String name; final int age;
User({required this.name, required this.age});
factory User.fromJson(Map<String, dynamic> json) => User( name: json['name'] as String, age: json['age'] as int, );}
// Function to parse JSON in an isolateFuture<List<User>> parseUsersInBackground(String jsonString) async { return await Isolate.run( (String json) { final List<dynamic> parsedList = jsonDecode(json) as List<dynamic>; return parsedList .map((item) => User.fromJson(item as Map<String, dynamic>)) .toList(); }, jsonString, );}
// Usage in your appFuture<void> loadUsers() async { final jsonString = /* your large JSON string */;
try { final users = await parseUsersInBackground(jsonString); // Update UI with parsed users } catch (e) { // Handle parsing errors }}Things to note while using Isolate
- if you’re calling any function for isolate, make sure that run doesn’t exists on the main thread. it should be independent from the main thread.