跳到主內容

在後臺解析 JSON

如何在後臺執行任務。

預設情況下,Dart 應用在單個執行緒上執行所有工作。在許多情況下,這種模型簡化了編碼,並且速度足夠快,不會導致應用效能下降或動畫卡頓,這通常被稱為“掉幀”(jank)。

然而,你可能需要執行昂貴的計算,例如解析一個非常大的 JSON 文件。如果這項工作耗時超過 16 毫秒,使用者就會感覺到掉幀。

為了避免掉幀,你需要使用單獨的 Isolate 在後臺執行此類昂貴的計算。本指南分為以下幾個步驟:

  1. 新增 `http` 包。
  2. 使用 http 包發起網路請求。
  3. 將響應轉換為照片列表。
  4. 將此工作移動到單獨的 isolate 中。

1. 新增 `http` 包

#

首先,將 http 包新增到你的專案中。http 包可以更輕鬆地執行網路請求,例如從 JSON 端點獲取資料。

要將 http 包新增為依賴項,請執行 flutter pub add

flutter pub add http

2. 發起網路請求

#

本示例涵蓋了如何使用 http.get() 方法從 JSONPlaceholder REST API 獲取包含 5000 個照片物件的大型 JSON 文件。

dart
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

dart
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>>

  1. 建立一個 parsePhotos() 函式,將響應主體轉換為 List<Photo>
  2. fetchPhotos() 函式中使用 parsePhotos() 函式。
dart
// 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 時會短暫凍結。這就是掉幀現象,你需要消除它。

你可以透過使用 Flutter 提供的 compute() 函式將解析和轉換過程移動到後臺 isolate 中來消除掉幀。compute() 函式在後臺 isolate 中執行昂貴的函式並返回結果。在本例中,即在後臺執行 parsePhotos() 函式。

dart
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 的說明

#

Isolate 透過來回傳遞訊息進行通訊。這些訊息可以是原始值(如 nullnumbooldoubleString),也可以是本例中 List<Photo> 這樣的簡單物件。

如果你嘗試在 isolate 之間傳遞更復雜的物件(例如 Futurehttp.Response),可能會遇到錯誤。

作為替代方案,請檢視 worker_managerworkmanager 包以進行後臺處理。

完整示例

#
dart
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);
      },
    );
  }
}

Isolate demo