Natesh bhat
Natesh bhat

Reputation: 13257

How to load a file from a specific package in flutter?

Here's my folder structure for the package core :

/pubspec.yaml
/assets
   |-images
   |-lang
       |- en.json
       |- hi.json

I have a similar structure for another module called moduleA

Now when I load the json file I load it like so :

    await rootBundle.loadString('assets/lang/en.json');

But issue is that when I use the screens of 'core' module in 'moduleA' , 'core' module looks inside the 'moduleA' to search for the filepath. What I need is a way to specify which package to load the file from :

Now I have already looked into the answer for the blow question and tried it but it didn't work for me:

How to use rootBundle in flutter to load images?

doing a rootBundle.loadString('packages/core/assets/lang/en.json') still gives me a file not found error despite having specified it in the pubspec.yaml file and copying the assets/ folder inside the core/lib folder.

So , when I load the String using :

await rootBundle.loadString('packages/core/assets/lang/${locale.languageCode}.json');

I am getting the following error :

Error: unable to find directory entry in pubspec.yaml: /Users/nateshmbhat/Desktop/nuclei-flutter-sdk/core/packages/core/assets/images/

Here is my core/pubspec.yaml content :

flutter:
  assets:
    - packages/core/assets/lang/
    - packages/core/assets/images/

I have moved the assets folder into core/lib/ .

Is there anything wrong I am doing here ? Any idea how to fix this ?

Upvotes: 3

Views: 1910

Answers (2)

Ced
Ced

Reputation: 17417

when building a package:

  • put your assets in the assets folder of the package as usual
  • add the assets/translations/ to pubspec, don't forget the last / as it means the whole dir
  • when using rootBundle.loadAsString or the likes the path will be packages/package_name/assets/translations/en.json. Note that packages is plural.

Upvotes: 5

Natesh bhat
Natesh bhat

Reputation: 13257

Turned out that when we import assets inside packages , we need to include specific files too and just a folder include doesn't work.

So doing the following fixed it :D

flutter:
  assets:
    - packages/core/assets/lang/en.json
    - packages/core/assets/lang/sp.json
    - packages/core/assets/images/myimage.png

Upvotes: -1

Related Questions