Search code examples
flutterdartassets

How to include file assets to be used by your own package in flutter


I have a package where I'm trying to load a string from my rootBundle. This file is to be used within the package itself only as part of internal configuration. I cant see where i'm going wrong.

This is my folder structure:

my-package
  --> lib
  --> pubspec.yaml
  --> assets/file.js

This is the content of my pubspec.yaml

flutter:
  assets:
    - assets/
    - assets/file.js

This is how i'm calling it

String js = await rootBundle.loadString('assets/file.js');

I keep on getting unable to load asset

Unable to load asset: assets/file.js

Solution

  • had the same problem but solved it by doing this:

    In your package's .yaml file, add this line to import the file/asset

    assets:
    - packages/<Package name>/assets/<File name>
    

    Replace the <Package name> with the name of your package, and <File name> with the name of said file/asset.

    Then place the file/asset in a folder under your lib directory of your package. The structure should look something like this:

    my_package
    --> lib
        --> assets
            file.js
    

    Make sure to add any additional folders to the reference if necessary.

    When referencing the file/asset in your app or package, use the same reference as in you .yaml file:

    String js = await rootBundle.loadString('packages/<Package name>/assets/file.js');
    

    For example, here I'm getting a .js file.