flutterpackageassetbundle

Flutter: How to get the local AssetBundle when being used as a package?


I am trying to nest 1 flutter application within another, think a Gallery App, that links to many Demo Apps:

Gallery

--> Demo1

--> Demo2

etc

Demo1 uses: rootBundle.load('images/image.png') to load images.

This breaks when Demo1 is used from within Gallery, presumably because rootBundle now refers to the Gallery Bundle, not Demo 1.

Is there a way I can architect Demo1 so it always pulls from it's own AssetBundle? I tried

bundle = DefaultAssetBundle.of(context);

but it does not seem to make a difference.

NOTE: I can work around this, by moving the images inside of /lib, and declaring them as 'packages/package_name/images/glow.png', and then using rootBundle.load('packages/package_name/images/glow.png'), however we're looking to avoid this requirement, and instead just access the correct AssetBundle.


Solution

  • I think you could wrap the screens or widgets of the included apps with a DefaultAssetBundle, and hand it a custom implementation of PlatformAssetBundle in which you overwrite its load(String) method. In it you prefix the key parameter with the package name. The package name could be provided as a constructor parameter of your custom implementation. Example:

    Container(
      child: DefaultAssetBundle(
        bundle: PackageAssetBundle(packageName: 'demo1'),
        child: Demo1WidgetWithPackageAssets(),
       ),
    )