0

最初的问题来自颤振问题 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/
4

1 回答 1

2

要从包中加载资产,您应该添加'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';

https://github.com/flutter/flutter/blob/fba99f6cf9a14512e461e3122c8ddfaa25394e89/packages/flutter/lib/src/painting/image_resolution.dart#L146

因此,为密钥添加前缀'packages/<package_name>/'将适用于上面的演示:

String value = await rootBundle
     .loadString('packages/<package_name>/lib/src/assets/JsonConfig/test.json');
于 2020-09-16T07:05:19.383 回答