Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Package Reading its Own Assets

I have an module with an 'assets' folder located in the same directory as my pubspec.yaml file. In my assets folder I have test.txt, and simpleObject.json.

flutter:
  assets:
    - assets/test.txt
    - assets/simpleObject.json

I believe the following code should then allow me to read it into my app.

var test = await DefaultAssetBundle.of(context).loadString("assets/test.txt");

Sadly I get the following error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Unable to load asset: assets/test.txt

The error comes from the asset_bundle.dart. I have to assume this is my fault, but according to everything I've read I'm doing it correctly. Any thoughts?

Here is my file structure if it helps.

MyModule
    |_assets/test.txt
    |_lib/
    |_pubspec.yaml
like image 476
eimmer Avatar asked May 29 '19 18:05

eimmer


People also ask

How do I read assets in Flutter?

How to Read Text File from Assets Folder: import 'package:flutter/services. dart'; String textasset = "assets/textfiles/file.

Where are assets stored in Flutter?

Flutter uses the pubspec.yaml file, located at the root of your project, to identify assets required by an app. Note: Only files located directly in the directory are included unless there are files with the same name inside a subdirectory (see Asset Variants).

How do I fix unable to load assets in Flutter?

To fix the unable to load asset in Flutter, you can either verify the image path that has correct image spelling or give a proper indentation in pubspec. yaml file.


1 Answers

I got a solution. Even though my package was trying to load its own asset, it still had to specify itself as the location.

Here is how my_package loads an image asset (specifying the package), uses it in a widget, and that widget is easily used by outside apps.

Image.asset(AssetImage("assets/splash.png").assetName, package: 'my_package',);
like image 117
eimmer Avatar answered Sep 27 '22 18:09

eimmer