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

主宰稳场 提交于 2020-03-05 00:36:56

问题


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 ?


回答1:


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


来源:https://stackoverflow.com/questions/60144352/how-to-load-a-file-from-a-specific-package-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!