How to read assets JSON file from different package in flutter?

Issue

I am working on a flutter app where I’m using multiple plugins for main app

main_app
-plugin1
 -example
-plugin2
 -example
-plugin3
 --example
package as well 
- <package_name>

every plugin have its own example folder which help me to test the UI and most of UI using common images and icons which is kept in pure flutter package separately:

framework_utilities:<--(package)
   assets:
    - assets/
    - assets/images/green/2x/
    - assets/mockup/reg_state.json <--- JSON file
   lib
     src
       constant

and I’m able to access images and icons by passing the package reference :

Image.asset("assets/barcode.png", package: "framework_utilities", width: 70.0, height: pad_30),

now my requirement is I want to mockup whole app without including json file to main application level.

It works fine if I include json file inside the assets folder in main application but I don’t want to make the copy of json file inside the plugin and application i want to keep it in a single place and read it.

I tried

rootBundle.loadString('assets/reg_state.json')

it works only individual plugin example level.

Why I need to read json file ?

If I mockup main app or individual plugin so I can provide a dummy json data to see the UI.

Solution

How i resolve the issue :

import the package and plugin inside your main app pubspec.yaml file

registration_plugin:
  path: ../registration_plugin  <--- this is plugin
framework_utils:
  path: ../framework_utils      <--- this is package

I have json files and icons in framework_utils assets folder like :

assets:
  - assets/
  - assets/images/green/2x/
  - assets/reg_state.json
  - assets/user_state.json

Now if you want to read this file or icons in plugin I’m calling like code below :

For image

Image.asset("assets/user.png", package: "framework_utils", width: 70.0, height: pad_30),

For JSON file

 String path = 'packages/framework_utils/assets/user_state.json';
 String jobsString = await rootBundle.loadString(path); 
 List<dynamic> users = await jsonDecode(jobsString);

This is the solution for me.

Answered By – Sanjeev Sangral

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.