Alex
Alex

Reputation: 91

Flutter rootBundle: Unhandled Exception: Unable to load asset within my package

Background

My app has several packages that I've developed on my own. My project structure is as follows:

/my_app
-  /lib
-  /my_packages
-    /package_1
-    /package_2
-    ...

Several of the packages change their behavior depending on the environment (iOS, Android, Web, dev/prod). For example, packages query "localhost" when in dev, but "www.example.com" in production.

Problem

I'd like to share the environment between packages. I figured that the best way to do that would be to develop another package. That way, I can import the package library to each of the other packages. The package looks as follows:

File Structure

/environment_pkg
-  /assets
-    /configs
-       config1.json
-       config2.json
-       ...

pubspec.yaml

flutter:

  assets:
    - assets/configs/config1.json
    - assets/configs/config2.json
    - ...

Loading Data

static Future<void> initialize(String name) async {
    final configString = await rootBundle.loadString('assets/configs/${name}.json');
    _config = json.decode(configString) as Map<String, dynamic>;
 }

Error

Unhandled Exception: Unable to load asset: assets/configs/config1.json

Summary

I am trying to load JSON files from the assets folder with a flutter package using rootBundle. Flutter is unable to locate the files.

Upvotes: 0

Views: 1576

Answers (1)

Anand A L
Anand A L

Reputation: 177

https://stackoverflow.com/a/74128378/12379401

Add packages/{packagename}/ before path

static Future<void> initialize(String name) async {
    final configString = await rootBundle.loadString('packages/{packagename}/assets/configs/${name}.json');
    _config = json.decode(configString) as Map<String, dynamic>;  }

Upvotes: 1

Related Questions