如何访问包中的资产
How to access assets in package
The original question comes from flutter issue 32799
我开发了一个 dart 包,我需要在运行时加载一些 json 文件,但是当我这样做时发生错误。加载图片没问题,代码:
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();
});
}
我的 pubspec.yaml 文件是这样的:
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/
要从包中加载资产,您应该添加前缀 'packages/<package_name>/'
作为使其工作的关键。
比如AssetImage
怎么做
/// 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';
因此,为密钥添加前缀 'packages/<package_name>/'
将适用于上面的演示:
String value = await rootBundle
.loadString('packages/<package_name>/lib/src/assets/JsonConfig/test.json');
The original question comes from flutter issue 32799
我开发了一个 dart 包,我需要在运行时加载一些 json 文件,但是当我这样做时发生错误。加载图片没问题,代码:
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();
});
}
我的 pubspec.yaml 文件是这样的:
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/
要从包中加载资产,您应该添加前缀 'packages/<package_name>/'
作为使其工作的关键。
比如AssetImage
怎么做
/// 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';
因此,为密钥添加前缀 'packages/<package_name>/'
将适用于上面的演示:
String value = await rootBundle
.loadString('packages/<package_name>/lib/src/assets/JsonConfig/test.json');