Assets

Flutter registers an image or font declared by a package under a packages/<package>/ prefix, and resolving it requires naming that package at the call site. A package cannot name itself, so adding package: 'my_app' to a resource your app declares makes it stop resolving in your app.

That means a resource declared in your app package cannot be referenced from both your app and your Widgetbook. Move it into a package that both depend on, and it gets one name that resolves in both.

  • Create the package

    Add a pubspec.yaml next to your images and fonts. No dependencies are needed.

    yaml
    design_system/pubspec.yaml
    name: design_system
    description: >
      Holds the images and fonts for the app, in a separate package
      so they can be shared with the Widgetbook app.
    
    version: 0.0.0
    publish_to: none
    
    environment:
      sdk: ">=3.1.0 &lt;4.0.0"
    
    flutter:
      assets:
        - .
      fonts:
        - family: My Custom Font
          fonts:
            - asset: fonts/MyCustomFont/MyCustomFont-Regular.otf
            - asset: fonts/MyCustomFont/MyCustomFont-Bold.otf
              weight: 700

    Font paths are relative to the package root.

  • Depend on it from both packages

    yaml
    pubspec.yaml
    dependencies:
      design_system:
        path: design_system
    yaml
    widgetbook/pubspec.yaml
    dependencies:
      design_system:
        path: ../design_system
  • Name the package at every call site

    dart
    Image.asset(
      'images/logo.png',
      package: 'design_system',
    )
    dart
    Text(
      label,
      style: const TextStyle(
        fontFamily: 'My Custom Font',
        package: 'design_system',
      ),
    )

    The package argument names the package that declares the resource, never the one referencing it, so it stays the same in your app, in your design system, and in your Widgetbook. A package that is only a transitive dependency still works.

See Fonts for font loading concerns that are not about packaging, such as google_fonts and Flutter's default fonts.

On this page