What are Asset Bundles in Flutter?

Topics covered:

  1. What is an asset Bundle — from the docs

  2. How to use assets from another package in Lottie and Rive

An asset bundle is A collection of resources used by the application.

From the docs

Asset bundles contain resources, such as images and strings, that can be used by an application. Access to these resources is asynchronous so that they can be transparently loaded over a network (e.g., from a NetworkAssetBundle) or from the local file system without blocking the application’s user interface.

Applications have a rootBundle, which contains the resources that were packaged with the application when it was built. To add resources to the rootBundle for your application, add them to the assets subsection of the flutter section of your application's pubspec.yaml manifest.

For example:

name: my_awesome_application
flutter:
  assets:
   - images/hamilton.jpeg
   - images/lafayette.jpeg

Rather than accessing the rootBundle global static directly, consider obtaining the AssetBundle for the current BuildContext using DefaultAssetBundle.of. This layer of indirection lets ancestor widgets substitute a different AssetBundle (e.g., for testing or localization) at runtime rather than directly relying upon the rootBundle created at build time. For convenience, the WidgetsApp or MaterialApp widget at the top of the widget hierarchy configures the DefaultAssetBundle to be the rootBundle.

How to access an asset from an asset bundle that is part of another package?

Few libraries provide built-in support for accessing this, whereas for other libraries we have to specify the path explicitly.

For example:

Lottie

Lottie.asset constructor provides a package parameter to specify the package name the asset is stored in.

Rive

Rive does not have such an option, so you need to provide the path in the below format.

packages/<package-name><asset-path> where package-name is the package that contains the asset and asset-path is the path of the asset from the package root directory. Or in other words, the path of the asset from the package root(package root included) which is prepended by packages/.

0
Subscribe to my newsletter

Read articles from NonStop io Technologies directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

NonStop io Technologies
NonStop io Technologies

Product Development as an Expertise Since 2015 Founded in August 2015, we are a USA-based Bespoke Engineering Studio providing Product Development as an Expertise. With 80+ satisfied clients worldwide, we serve startups and enterprises across San Francisco, Seattle, New York, London, Pune, Bangalore, Tokyo and other prominent technology hubs.