移除 AssetManifest.json
概述
#Flutter 應用曾包含一個名為 AssetManifest.json 的資原始檔。該檔案實際上包含了一個資源列表。應用程式程式碼可以使用 AssetBundle API 讀取它,以確定執行時有哪些可用的資源。
AssetManifest.json 檔案是一個未公開的實現細節。它已不再被框架使用,並且計劃在未來的 Flutter 版本中不再生成它。如果你的應用程式程式碼需要獲取可用資源的列表,請改用 AssetManifest API。
遷移指南
#從 Flutter 應用程式程式碼讀取資源清單
#之前
dart
import 'dart:convert';
import 'package:flutter/services.dart';
void readAssetList() async {
final assetManifestContent = await rootBundle.loadString('AssetManifest.json');
final decodedAssetManifest =
json.decode(assetManifestContent) as Map<String, Object?>;
final assets = decodedAssetManifest.keys.toList().cast<String>();
}之後
dart
import 'package:flutter/services.dart';
void readAssetList() async {
final assetManifest = await AssetManifest.loadFromAssetBundle(rootBundle);
final 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 pathToAssetManifest = './build/web/assets/AssetManifest.bin';
final manifest = File(pathToAssetManifest).readAsBytesSync();
final decoded = const StandardMessageCodec()
.decodeMessage(ByteData.sublistView(manifest));
final assets = decoded.keys.cast<String>().toList();
}請注意,AssetManifest.bin 是 Flutter 的一個實現細節。讀取此檔案不是官方支援的工作流程。該檔案的內容或格式可能會在未來的 Flutter 版本中更改,恕不另行通知。
時間線
#AssetManifest.json 將從 3.19 之後的第四個穩定版本,或者自 3.19 釋出之日起一年後(以較晚者為準)開始不再生成。
參考資料
#相關問題
- 構建 Flutter 應用時,flutter 工具會生成一個框架未使用過的
AssetManifest.json檔案 (Issue #143577)
相關 PR