You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法加载AssetManifest.json,Flutter资产列表输出为空的问题排查

Flutter 问题:读取AssetManifest.json后资产列表为空

问题详情

尝试通过AssetManifest.json加载assets/DB/paper目录下的.json文件,代码执行后输出空数组,无法获取目标资产路径。

代码片段

Future<void> uploadData() async {
    final assetsManifest = await DefaultAssetBundle.of(Get.context!)
        .loadString('AssetManifest.json');
    final assets = json.decode(assetsManifest).keys;

    final manifestContent = await DefaultAssetBundle.of(Get.context!)
        .loadString("AssetManifest.json");
    final Map<String, dynamic> manifestMap = json.decode(manifestContent);
    final papersInAssets = manifestMap.keys
        .where((path) =>
            path.startsWith("assets/DB/paper") && path.contains(".json"))
        .toList();
    print(papersInAssets);
}

项目结构

目标.json文件存放于assets/DB/paper目录下。

实际运行输出

started application in 2,750ms.
[GETX] Instance "DataUploader" has been created
[GETX] Instance "DataUploader" has been initialized
[GETX] Instance "GetMaterialController" has been created
[GETX] Instance "GetMaterialController" has been initialized
I/flutter (12563): []

解决方法

1. 确认pubspec.yaml的资产配置

Flutter只会打包pubspec.yaml中声明的资产,确保配置正确:

flutter:
  assets:
    - assets/DB/paper/  # 包含该目录下所有文件及子目录

修改配置后执行flutter pub get,并重启应用(热重载可能不生效)。

2. 打印所有资产路径验证

先打印AssetManifest中的所有路径,确认目标文件是否被正确打包:

final manifestContent = await DefaultAssetBundle.of(Get.context!).loadString("AssetManifest.json");
final Map<String, dynamic> manifestMap = json.decode(manifestContent);
print("所有资产路径:${manifestMap.keys.toList()}");

如果目标路径不在输出中,说明资产未被打包,回到第一步检查配置。

3. 替换为rootBundle加载

若Get.context!存在上下文失效的可能,改用rootBundle直接加载(无需上下文):

final manifestContent = await rootBundle.loadString("AssetManifest.json");

4. 清理缓存后重新构建

缓存可能导致资产未更新,执行以下命令清理并重建:

flutter clean
flutter pub get
flutter run

内容的提问来源于stack exchange,提问作者Harsh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:25:16