Search code examples
flutterflutter-dependenciesflutter-packages

How to access assets in package


The original question comes from flutter issue 32799

I develop a dart package, i need load some json file in runtime, but when I do this occur an error. load image is no problem ,the code:

void main() {
  Future<void> loadAsset() async {
    String value = await rootBundle
        .loadString('lib/src/assets/JsonConfig/test.json');

    //Image img = Image.asset('lib/src/assets/default-logo.png');
  }

  test('adds one to input values', () async {
    await loadAsset();
  });
}

my pubspec.yaml file like this:

flutter:
  # To add assets to your package, add an assets section, like this:
   assets:
   - lib/src/assets/default-logo.png
   - lib/src/assets/JsonConfig/test.json
   - lib/src/assets/

Solution

  • To load assets from packages, you should add the prefix 'packages/<package_name>/' for the key to making it works.

    Such as how AssetImage do

    /// The name used to generate the key to obtain the asset. For local assets
    /// this is [assetName], and for assets from packages the [assetName] is
    /// prefixed 'packages/<package_name>/'.
    String get keyName => package == null ? assetName : 'packages/$package/$assetName';
    

    https://github.com/flutter/flutter/blob/fba99f6cf9a14512e461e3122c8ddfaa25394e89/packages/flutter/lib/src/painting/image_resolution.dart#L146

    So add the prefix 'packages/<package_name>/' for the key will work on the demo above:

    String value = await rootBundle
         .loadString('packages/<package_name>/lib/src/assets/JsonConfig/test.json');