littlegnal
littlegnal

Reputation: 515

How to access assets in package

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

Answers (2)

Yauheni Prakapenka
Yauheni Prakapenka

Reputation: 1714

How to use assets from an external package in flutter

module a with icon:

  1. pubspec.yaml
name: module_a

environment:
  sdk: '>=3.1.3 <4.0.0'

dependencies:
  flutter:
    sdk: flutter

flutter:
  assets:
    - lib/
  1. Move icon to lib/active.svg

module b with icon dependency

  1. pubspec.yaml
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

  1. test drive in lib/main.dart
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

littlegnal
littlegnal

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';

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

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

Related Questions