跳到主内容

在后台解析 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