resolveShaderBundleKey function Assets and loading

Future<String> resolveShaderBundleKey(
  1. String bundleName, {
  2. String? package,
  3. AssetBundle? bundle,
})

Resolves the asset key of a shader bundle built by buildTargetShaderBundleJson (or flutter_gpu_shaders' buildShaderBundleJson), by its bundle name.

Hand the result to loadShaderLibraryAsync. Pass package to disambiguate when more than one package in the app builds a bundle of the same name.

final key = await resolveShaderBundleKey('my', package: 'my_app');
final library = await gpu.loadShaderLibraryAsync(key);

Implementation

Future<String> resolveShaderBundleKey(
  String bundleName, {
  String? package,
  AssetBundle? bundle,
}) async {
  final name = bundleName.endsWith('.shaderbundle')
      ? bundleName.substring(0, bundleName.length - '.shaderbundle'.length)
      : bundleName;
  final dataAssetSuffix =
      '/flutter_gpu_shaders/shaderbundles/$name.shaderbundle';
  // Collected inside the guard, judged outside it, so an ambiguity is reported
  // rather than swallowed by the missing-manifest fallback.
  var matches = const <String>[];
  try {
    final keys = (await AssetManifest.loadFromAssetBundle(
      bundle ?? rootBundle,
    )).listAssets();
    matches = keys
        .where(
          (key) =>
              key.endsWith(dataAssetSuffix) &&
              (package == null || key.startsWith('packages/$package/')),
        )
        .toList();
  } catch (_) {
    // No manifest here; the generated index below is the only source.
  }
  if (matches.length == 1) return matches.single;
  if (matches.length > 1) {
    throw StateError(
      'Multiple shader bundles named "$name" were found: '
      '${matches.join(', ')}. Pass package to disambiguate.',
    );
  }
  final index = await loadGeneratedAssetIndex(bundle);
  final key = index.resolveKey(
    GeneratedAssetFamily.shaderBundle,
    name,
    package: package,
  );
  if (key != null) return key;
  throw StateError(
    'No shader bundle named "$name" was found. '
    '${generatedAssetFixHint('shader bundles')}',
  );
}