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

如何访问Flutter资源文件夹文件并统计主/子目录文件数量

Flutter资源文件数量统计问题解决

问题原因

  • AssetManifest.json是Flutter构建时自动生成的文件,不会出现在项目源码目录中,它打包在最终应用包(APK/IPA/App Bundle)内,记录了所有被Flutter识别的资源文件,包括:
    • 你手动放在assets目录下的文件
    • Flutter框架自身的资源(如字体、图标)
    • 依赖包中包含的资源文件
    • 构建过程中生成的衍生文件(如不同分辨率的图片变体)

解决方案:过滤目标目录资源

要只统计指定的资源主目录及子目录文件,需对AssetManifest.json返回的路径列表进行过滤,只保留符合目标路径前缀的条目。

修改后的代码示例:

FutureBuilder<String>(
  future: DefaultAssetBundle.of(context).loadString('AssetManifest.json'),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      Map? jsonMap = json.decode(snapshot.data!);
      // 指定你要统计的资源根目录,比如 'assets/images/'
      const targetDirPrefix = 'assets/';
      // 过滤出以目标目录开头的文件路径,排除目录本身
      List<String> targetFiles = jsonMap?.keys.where((path) {
            return path.startsWith(targetDirPrefix) && !path.endsWith('/');
          }).toList() ?? [];
      
      print('目标目录文件数量:${targetFiles.length}');
      // 打印部分文件路径确认过滤结果
      if(targetFiles.isNotEmpty) {
        print('示例文件路径:${targetFiles.take(5).join(', ')}');
      }

      return GridView.builder(
        physics: const NeverScrollableScrollPhysics(),
        padding: const EdgeInsets.symmetric(horizontal: 15),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 5,
          mainAxisSpacing: 1,
          mainAxisExtent: 60,
          crossAxisSpacing: 15,
        ),
        itemCount: targetFiles.length,
        itemBuilder: (context, index) {
          return Text(
            '${index + 1}',
            style: Theme.of(context).textTheme.headline2,
          );
        },
      );
    }
    return Center(
      child: Text('Loading...'),
    );
  },
),

额外说明

  • 若有多个目标资源目录(如assets/images/和assets/audio/),可调整过滤条件为path.startsWith('assets/images/') || path.startsWith('assets/audio/')
  • 注意路径大小写:不同平台对资源路径的大小写处理有差异,确保过滤前缀与pubspec.yaml中配置的路径一致
  • AssetManifest.json中的路径相对项目根目录,与pubspec.yaml的assets字段配置路径对应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:15:20