Reputation: 515
The original question comes from flutter issue 32799
I develop a dart package, i need load some json file in runtime, but when I do this occur an error. load image is no problem ,the code:
void main() {
Future<void> loadAsset() async {
String value = await rootBundle
.loadString('lib/src/assets/JsonConfig/test.json');
//Image img = Image.asset('lib/src/assets/default-logo.png');
}
test('adds one to input values', () async {
await loadAsset();
});
}
my pubspec.yaml file like this:
flutter:
# To add assets to your package, add an assets section, like this:
assets:
- lib/src/assets/default-logo.png
- lib/src/assets/JsonConfig/test.json
- lib/src/assets/
Upvotes: 9
Views: 7446
Reputation: 1714
How to use assets from an external package in flutter
module a with icon:
name: module_a
environment:
sdk: '>=3.1.3 <4.0.0'
dependencies:
flutter:
sdk: flutter
flutter:
assets:
- lib/
module b with icon dependency
name: module_b
environment:
sdk: '>=3.1.3 <4.0.0'
dependencies:
flutter:
sdk: flutter
flutter_svg: ^2.0.8
module_a:
path: ../module_a
flutter:
assets:
- packages/module_a/active.svg
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SvgPicture.asset('packages/module_a/active.svg'),
);
}
}
Upvotes: 2
Reputation: 515
To load assets from packages, you should add the prefix 'packages/<package_name>/'
for the key to making it works.
Such as how AssetImage
do
/// The name used to generate the key to obtain the asset. For local assets
/// this is [assetName], and for assets from packages the [assetName] is
/// prefixed 'packages/<package_name>/'.
String get keyName => package == null ? assetName : 'packages/$package/$assetName';
So add the prefix 'packages/<package_name>/'
for the key will work on the demo above:
String value = await rootBundle
.loadString('packages/<package_name>/lib/src/assets/JsonConfig/test.json');
Upvotes: 19