Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Package can't load a string resource using rootBundle.loadString - asset indenting correct

I have a project that consumes another package on the drive using a relative path:

project1 (setup as a full flutter project with flutter create project1)

project2 (setup with flutter create --template=package

project1's packages.yaml does this: dependancies: project1: path: ../project2

project2's packages.yaml does this:

flutter: assets: - lang/en.json

Which works and everything sees everything else and there is no complaint about that path for the asset and I've verified that it has exactly 2 spaces before assets: and exactly 4 actual spaces beofre - lang/en.json

The problem occurs when project2 tries to load lang/en.json like this in code form project2:

final jsonString = await rootBundle.loadString('lang/en.json');

I get an "asset could not be loaded ${key}" on the loadString function.

if however I take exactly the same code and put it on project1 and copy the folder exactly and copy the exact same asset tag in packages.yaml, project1 has no problem loading the file. If I even leave the asset links on the project1 then project2 can load them just fine too.

Is this a bug, or am I doing something wrong with the package template version?

like image 275
James Hancock Avatar asked Oct 20 '25 11:10

James Hancock


1 Answers

I have same issue. and I found the solution: In project2, do some steps as below:

  1. create assets folder
  2. create lang folder(or any other folder name)
  3. create json file in lang folder. Ex: en.json, vi.json...
  4. in pubspec.yaml of project, you need to declare assets:
flutter:
  assets:
    - assets/lang/vi.json
    - assets/lang/en.json
  1. when using loadString then the path will be :
await rootBundle.loadString('packages/language_pack/assets/langen.json');

Note that packages is plural and language_pack is package name

like image 121
Trung Đoan Avatar answered Oct 22 '25 04:10

Trung Đoan