在後臺解析 JSON
預設情況下,Dart 應用的所有工作都在單個執行緒上完成。在許多情況下,這種模型簡化了編碼,並且速度足夠快,不會導致應用效能不佳或動畫卡頓,這通常稱為“jank”。
但是,您可能需要執行昂貴的計算,例如解析非常大的 JSON 文件。如果這項工作花費的時間超過 16 毫秒,使用者就會體驗到 jank。
為了避免 jank,您需要使用單獨的 Isolate 在後臺執行此類昂貴的計算。本食譜使用以下步驟:
- 新增 `http` 包。
- 使用
http包發起網路請求。 - 將響應轉換為照片列表。
- 將此工作移至單獨的 Isolate。
1. 新增 `http` 包
#首先,將 http 包新增到您的專案中。http 包可以更輕鬆地執行網路請求,例如從 JSON 端點獲取資料。
要將 http 包新增為依賴項,請執行 flutter pub add。
flutter pub add http2. 發起網路請求
#此示例涵蓋了如何使用 JSONPlaceholder REST API 中的 http.get() 方法,獲取包含 5000 個照片物件的列表的大型 JSON 文件。
Future<http.Response> fetchPhotos(http.Client client) async {
return client.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
}3. 解析 JSON 並將其轉換為照片列表
#接下來,遵循 從網際網路獲取資料 食譜中的指導,將 http.Response 轉換為 Dart 物件列表。這使得資料更容易處理。
建立 Photo 類
#首先,建立一個包含照片資料的 Photo 類。包括一個 fromJson() 工廠方法,以便於從 JSON 物件建立 Photo。
class Photo {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;
const Photo({
required this.albumId,
required this.id,
required this.title,
required this.url,
required this.thumbnailUrl,
});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
albumId: json['albumId'] as int,
id: json['id'] as int,
title: json['title'] as String,
url: json['url'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
);
}
}將響應轉換為照片列表
#現在,使用以下說明更新 fetchPhotos() 函式,使其返回 Future<List<Photo>>。
- 建立一個
parsePhotos()函式,該函式將響應體轉換為List<Photo>。 - 在
fetchPhotos()函式中使用parsePhotos()函式。
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed = (jsonDecode(responseBody) as List<Object?>)
.cast<Map<String, Object?>>();
return parsed.map<Photo>(Photo.fromJson).toList();
}
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client.get(
Uri.parse('https://jsonplaceholder.typicode.com/photos'),
);
// Synchronously run parsePhotos in the main isolate.
return parsePhotos(response.body);
}4. 將此工作移至單獨的 Isolate
#如果在較慢的裝置上執行 fetchPhotos() 函式,您可能會注意到應用在解析和轉換 JSON 時會短暫凍結。這是 jank,您應該將其消除。
您可以透過使用 Flutter 提供的 compute() 函式將解析和轉換移至後臺 Isolate 來消除 jank。compute() 函式在後臺 Isolate 中執行昂貴的函式並返回結果。在本例中,在後臺執行 parsePhotos() 函式。
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client.get(
Uri.parse('https://jsonplaceholder.typicode.com/photos'),
);
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
}關於使用 Isolate 的注意事項
#Isolates 透過來回傳遞訊息進行通訊。這些訊息可以是原始值,例如 null、num、bool、double 或 String,或者簡單的物件,例如此示例中的 List<Photo>。
如果您嘗試在 Isolates 之間傳遞更復雜物件(例如 Future 或 http.Response)可能會遇到錯誤。
作為替代解決方案,可以檢視 worker_manager 或 workmanager 包以進行後臺處理。
完整示例
#import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client.get(
Uri.parse('https://jsonplaceholder.typicode.com/photos'),
);
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed = (jsonDecode(responseBody) as List<Object?>)
.cast<Map<String, Object?>>();
return parsed.map<Photo>(Photo.fromJson).toList();
}
class Photo {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;
const Photo({
required this.albumId,
required this.id,
required this.title,
required this.url,
required this.thumbnailUrl,
});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
albumId: json['albumId'] as int,
id: json['id'] as int,
title: json['title'] as String,
url: json['url'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const appTitle = 'Isolate Demo';
return const MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late Future<List<Photo>> futurePhotos;
@override
void initState() {
super.initState();
futurePhotos = fetchPhotos(http.Client());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: FutureBuilder<List<Photo>>(
future: futurePhotos,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Center(child: Text('An error has occurred!'));
} else if (snapshot.hasData) {
return PhotosList(photos: snapshot.data!);
} else {
return const Center(child: CircularProgressIndicator());
}
},
),
);
}
}
class PhotosList extends StatelessWidget {
const PhotosList({super.key, required this.photos});
final List<Photo> photos;
@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: photos.length,
itemBuilder: (context, index) {
return Image.network(photos[index].thumbnailUrl);
},
);
}
}