跳至主要內容

移除 AssetManifest.json

摘要

#

Flutter 應用程式目前包含一個名為 AssetManifest.json 的資源檔案。此檔案實際上包含一個資源列表。應用程式程式碼可以使用 AssetBundle API 來讀取它,以確定運行時有哪些可用資源。

AssetManifest.json 檔案是一個未記錄的實作細節。框架不再使用它,因此在未來版本的 Flutter 中將不再生成它。如果您的應用程式程式碼需要取得可用資源的列表,請改用 AssetManifest API。

遷移指南

#

從 Flutter 應用程式程式碼讀取資源清單

#

之前

dart
import 'dart:convert';
import 'package:flutter/services.dart';

final String assetManifestContent = await rootBundle.loadString('AssetManifest.json');
final Map<Object?, Object?> decodedAssetManifest = 
    json.decode(assetManifestContent) as Map<String, Object?>;
final List<String> assets = decodedAssetManifest.keys.toList().cast<String>();

之後

dart
import 'package:flutter/services.dart';

final AssetManifest assetManifest = await AssetManifest.loadFromAssetBundle(rootBundle);
final List<String> assets = assetManifest.listAssets();

從 Flutter 應用程式外部的 Dart 程式碼讀取資源清單資訊

#

flutter CLI 工具會產生一個新的檔案 AssetManifest.bin。這取代了 AssetManifest.json。此檔案包含與 AssetManifest.json 相同的資訊,但格式不同。如果您需要從不屬於 Flutter 應用程式的程式碼讀取此檔案,因此無法使用 AssetManifest API,您仍然可以自行解析該檔案。

可以使用 standard_message_codec 套件來解析內容。

dart
import 'dart:io';
import 'dart:typed_data';

import 'package:standard_message_codec/standard_message_codec.dart';

void main() {
  // The path to AssetManifest.bin depends on the target platform.
  final String pathToAssetManifest = './build/web/assets/AssetManifest.bin';
  final Uint8List manifest = File(pathToAssetManifest).readAsBytesSync();
  final Map<Object?, Object?> decoded = const StandardMessageCodec()
      .decodeMessage(ByteData.sublistView(manifest));
  final List<String> assets = decoded.keys.cast<String>().toList();
}

請記住,AssetManifest.bin 是 Flutter 的實作細節。讀取此檔案不是官方支援的工作流程。檔案的內容或格式可能會在未來的版本中變更,恕不另行通知。

時間軸

#

從 3.19 版本之後的第四個穩定版本或 3.19 版本發布一年後(以較晚者為準)開始,將不再生成 AssetManifest.json

參考資料

#

相關問題

  • 在建置 Flutter 應用程式時,flutter 工具會產生一個框架未使用的 AssetManifest.json 檔案 (Issue #143577)