skip to content

Bundled Resources

How a Flutter app declares, loads and shows packaged files: pubspec asset entries, image providers and caching, custom fonts, and icons and vectors. Interviewers probe load paths and memory.

part ofFlutteroverview, primer and where to startread it →
on this pageshow

explore

questions

21

In Flutter, how do you bundle offline JSON question packs and sound files with an app and read them at runtime?

level: juniorimportance: must knowfreq 64%

answer

  1. flutter: then assets: in pubspec.yaml
  2. trailing slash = one directory level
  3. the declared path is the key
  4. rootBundle.loadString returns a Future
  5. build error vs runtime error

basics

~20 s

List the files or directories under flutter: assets: in pubspec.yaml, which copies them into the app's asset bundle, then read them by their declared path: rootBundle.loadString for text such as JSON, rootBundle.load for bytes such as sounds.

solid answer

~40 s

Assets are declared in `pubspec.yaml` under `flutter:` then `assets:`, each entry a path relative to the pubspec. A file path adds that file; a path ending in `/` adds the files *directly* in that directory, so each subdirectory needs its own entry. At build time the `flutter` tool copies them into the asset bundle, and at runtime you read them by the same path used as a key: `rootBundle.loadString('assets/questions/history.json')` returns a `Future<String>`, and `rootBundle.load(...)` returns `Future<ByteData>` for binary files like sounds. A declared file that is missing fails the build with `No file or variants found`; loading an undeclared key fails at runtime with `Unable to load asset`.

code

yaml · 6 lines
yaml
flutter:
  uses-material-design: true
  assets:
    - assets/questions/
    - assets/sounds/
    - assets/sounds/effects/

go deeper

for a junior

Know the pubspec syntax, that a trailing slash adds one directory level, and that rootBundle.loadString and load read files by their declared path.

for a middle

Explain the build step that copies files into the asset bundle, the difference between build-time and runtime errors, and why reads are asynchronous.

for a senior

Organise assets so large packs load lazily and declarations stay in step with the folders, and use AssetManifest instead of hard-coded lists.

for a principal

Decide which content ships in the binary as assets and which is downloaded later, weighing offline play against app size and update speed.

## What an asset is An **asset** is a file that ships inside the app and can be read at runtime: JSON data, configuration, images, audio, shaders. Unlike a file in the device's documents directory, it is read-only and identical on every install. A trivia game that must work offline is a typical case: its question packs are JSON files, and its "correct" and "wrong" sounds are audio files, all bundled with the build. ## Declaring assets in pubspec.yaml Assets are listed in the app's `pubspec.yaml`, under the `flutter:` section: ```yaml flutter: uses-material-design: true assets: - assets/questions/ - assets/sounds/ - assets/sounds/effects/ - assets/credits.txt ``` The rules the `flutter` tool applies: - Each entry is a path **relative to `pubspec.yaml`**. The folder name `assets` is a convention, not a requirement. - An entry ending in **`/`** includes every file **directly** in that directory. Subdirectories are **not** included, which is why `assets/sounds/effects/` needs its own line. (Resolution-aware image variants such as `2.0x/` folders are the one exception.) - An entry without a trailing slash names one file. - The order of entries does not matter. - **Indentation matters.** `assets:` must sit two spaces under `flutter:`; a mis-indented list is a common cause of the error `unable to find directory entry in pubspec.yaml`. An entry can also be a map with a `path:` key plus extra keys such as `transformers:` or `platforms:`, for build-time processing or per-platform bundling. ## How the files reach the app 1. On `flutter run` or `flutter build`, the tool reads the `assets:` list and copies each matching file into the **asset bundle**, a special archive packaged with the app. 2. If a declared file does not exist, the tool reports `No file or variants found for` that asset. 3. At runtime, code asks an `AssetBundle` for a **key**, which is the declared path, such as `assets/questions/history.json`. Keys match exactly, including case. ## Reading assets at runtime `package:flutter/services.dart` exposes **`rootBundle`**, the bundle built with the app: | Call | Returns | Typical use | |---|---|---| | `rootBundle.loadString(key)` | `Future<String>` (UTF-8) | JSON question packs, text | | `rootBundle.load(key)` | `Future<ByteData>` | sounds, binary data | | `rootBundle.loadStructuredData(key, parser)` | `Future<T>` | text parsed once into a model | Inside widgets, `DefaultAssetBundle.of(context)` is preferred, because it lets an ancestor substitute another bundle; it falls back to `rootBundle`. Images normally go through `Image.asset`, which resolves the bundle and resolution variants for you. Every call is asynchronous, so start the load once, in a repository or in `initState`, rather than in `build()`. Turning the JSON string into Dart objects is a separate step handled by `dart:convert` or generated models. ## Bundling only for some platforms Since Flutter 3.41 an entry can carry a `platforms:` list, so a large asset ships only where it is used. Valid values are `android`, `ios`, `web`, `linux`, `macos` and `windows`: ```yaml flutter: assets: - path: assets/sounds/desktop_ambience/ platforms: - macos - windows - linux ``` A phone build then leaves those files out entirely, and code that might run on every platform must not assume the asset exists everywhere. Platform code can read bundled assets too, through `AssetManager` on Android and `NSBundle` on iOS, which matters when a native plugin needs the same sound file. ## Two different failures | Symptom | Cause | |---|---| | Build prints `No file or variants found for ...` | a declared file is missing or misspelled on disk | | Build prints `unable to find directory entry in pubspec.yaml` | a declared directory is missing, often from bad indentation | | Runtime `Unable to load asset: "..."` | the key was never declared, or it differs from the declared path | ## Common mistakes - Expecting a directory entry to pull in its subfolders. - Loading `questions/history.json` when the declared path is `assets/questions/history.json`. - Using `dart:io` `File('assets/...')`: bundled assets are not ordinary files on the device, so read them through an `AssetBundle`. - Calling `rootBundle` in `main()` before `WidgetsFlutterBinding.ensureInitialized()`.

  • Why can't the app open a bundled question pack with File('assets/questions/history.json')?
    Bundled assets live inside the app package, not as plain files at that path on the device, so `dart:io` cannot open them by their pubspec path. Read them through an `AssetBundle` (`rootBundle` or `DefaultAssetBundle.of(context)`), which knows how to fetch them on every platform, including the web.
  • How can the app list every bundled question pack without hard-coding file names?
    Load the asset manifest with `AssetManifest.loadFromAssetBundle(rootBundle)` and call `listAssets()`, then filter keys that start with `assets/questions/`. Do not read `AssetManifest.json`: it was an undocumented detail, and current Flutter no longer generates it.

saying these in an interview costs you the question

  • An entry like assets/sounds/ also includes every subdirectory under it.
  • Any file in the project folder can be loaded without declaring it.
  • The asset key is just the file name, without its folder path.
  • Bundled assets can be opened with dart:io File using their pubspec path.
  • The order of entries under assets: changes which file wins.
open as a page

In Flutter, how do you bundle a custom font family in pubspec.yaml and apply it app-wide and to a single Text widget?

level: juniorimportance: must knowfreq 55%

basics

~20 s

Copy the font files into the project, list them in pubspec.yaml under flutter: fonts: as a family with asset entries, then pass that family name as fontFamily to ThemeData for the whole app or to a TextStyle for one widget.

open as a page

In Flutter, how does the Icon widget draw Icons and CupertinoIcons glyphs, and what must pubspec.yaml declare for each set?

level: juniorimportance: must knowfreq 55%

basics

~20 s

Icon draws one character of an icon font. Icons entries are const IconData code points in the MaterialIcons font, bundled only with uses-material-design: true; CupertinoIcons use the CupertinoIcons font from the cupertino_icons package, which must be a dependency.

open as a page

In Flutter, how do Image.asset, Image.network, Image.file and Image.memory differ, and what do all four have in common?

level: juniorimportance: must knowfreq 66%

basics

~20 s

Each constructor wraps a different ImageProvider: AssetImage for bundled files, NetworkImage for URLs, FileImage for device files and MemoryImage for bytes. All decode through the same in-memory ImageCache and accept cacheWidth, cacheHeight, the loading, frame and error builders, and gaplessPlayback.

open as a page

In Flutter, how are 2.0x and 3.0x image asset variants chosen for a device, and what must pubspec.yaml declare?

level: middleimportance: must knowfreq 46%

basics

~20 s

Put higher-resolution copies in sibling folders such as 2.0x/ and 3.0x/ and declare only the main asset or its directory; Flutter bundles the variants, and AssetImage picks the one closest to the device pixel ratio, rendering it at the main asset's logical size.

open as a page

In Flutter, what do cacheWidth and cacheHeight do on Image.network, and why can they stop a photo gallery from running out of memory?

level: middleimportance: must knowfreq 55%

basics

~20 s

They make the engine decode the image at the given pixel size instead of full resolution. Decoded images cost width × height × 4 bytes, so a 4000 × 3000 photo takes about 48 MB however small its JPEG; decoding at thumbnail size cuts that sharply.

open as a page

In Flutter, what do AssetBundle's load, loadString and loadStructuredData return, and which of their results does rootBundle cache?

level: middleimportance: should knowfreq 30%

basics

~20 s

load returns ByteData and is never cached; loadString returns a UTF-8 String that rootBundle caches for the bundle's lifetime unless cache: false; loadStructuredData runs your parser once per key and caches the parsed result, but not failures.

open as a page

In Flutter, how do you declare and load assets that live in a package, such as a shared trivia-content package?

level: middleimportance: should knowfreq 28%

basics

~20 s

A package declares its assets in its own pubspec.yaml, and they are bundled into every app that depends on it under the key packages/<package>/<path>. Load them with that full key, or pass package: to AssetImage or Image.asset.

open as a page

In Flutter, what is the difference between rootBundle and DefaultAssetBundle.of(context), and when would you use each?

level: middleimportance: should knowfreq 36%

basics

~20 s

rootBundle is the global bundle built with the app. DefaultAssetBundle.of(context) returns the bundle provided by the nearest DefaultAssetBundle ancestor, or rootBundle when there is none, so widgets using it can be given a different bundle for tests, localization or downloaded content.

open as a page

In Flutter, how does an app use a font family that a dependency package declares, and what does TextStyle's package argument change?

level: middleimportance: should knowfreq 28%

basics

~20 s

A package's declared fonts are registered as packages/<package>/<family>, so the app selects one with TextStyle(fontFamily: 'Scribbly', package: 'story_fonts'), which prefixes the name. Undeclared files under the package's lib/ can instead be declared by the app.

open as a page

In a Flutter pubspec.yaml font family, what do weight and style entries describe, and which file renders when a TextStyle requests an undeclared weight?

level: middleimportance: should knowfreq 40%

basics

~20 s

Weight and style entries describe which face each file is — a weight from 100 to 900 and normal or italic — and cannot change it. A TextStyle gets the closest bundled face; with no close one, Flutter may fake bold or italic.

open as a page

In Flutter, how do you ship custom brand icons as an icon font, and why must each IconData for that font be const?

level: middleimportance: should knowfreq 35%

basics

~20 s

Generate one font from the icon SVGs, declare it as a family in pubspec.yaml, and expose each glyph as a static const IconData. Release builds subset icon fonts by finding const IconData values, so a non-const one stops the build.

open as a page

In a Flutter app, where are the launcher icon and native splash screen defined, and why can't a Flutter widget replace the native splash?

level: middleimportance: should knowfreq 38%

basics

~10 s

Both are native resources: Android icons in res/mipmap folders, iOS icons in Runner's Assets.xcassets; the splash is Android's LaunchTheme background and iOS's LaunchScreen.storyboard. They appear before Dart runs, so no widget can draw them.

open as a page

In Flutter, how do an Image's loadingBuilder, frameBuilder and errorBuilder differ, and how would you use them for a listing photo?

level: middleimportance: should knowfreq 44%

basics

~20 s

loadingBuilder reports download progress and is called with null once loading completes; frameBuilder learns when the first frame is ready, for placeholders and fade-ins; errorBuilder replaces the image when loading fails. When both are set, loadingBuilder's child is frameBuilder's result.

open as a page

In a Flutter photo viewer, how do precacheImage and gaplessPlayback each prevent a blank flash when the user swipes to the next listing photo?

level: middleimportance: should knowfreq 33%

basics

~20 s

precacheImage decodes the next photo into the ImageCache before it is shown, so the swipe finds it ready. gaplessPlayback, false by default, keeps an Image showing its old picture while a changed provider loads, instead of going blank.

open as a page

With Flutter's google_fonts package, how are fonts fetched and cached at runtime, and when should a release build bundle the font files instead?

level: seniorimportance: should knowfreq 38%

basics

~20 s

google_fonts looks for each face in the app's assets, then a device cache, then downloads it over HTTP and caches it. Ship the files as assets and set allowRuntimeFetching to false when text must render offline and without a font swap.

open as a page

In Flutter, when should brand SVGs render through flutter_svg's SvgPicture versus precompiled vector_graphics, and what does each cost at runtime?

level: seniorimportance: should knowfreq 40%

basics

~20 s

SvgPicture parses SVG XML on the device and caches the result; precompiling with vector_graphics_compiler moves parsing and path optimisation to build time, so VectorGraphic only decodes a compact binary. Precompile static brand art; parse at runtime only SVGs that arrive later.

open as a page

A Flutter real-estate gallery of large remote photos crashes with out-of-memory on older phones; how does ImageCache behave, and what would you change?

level: seniorimportance: should knowfreq 40%

basics

~20 s

ImageCache keeps up to 1000 decoded images or 100 MiB, but images still on screen are live and not counted. Such crashes usually come from decoding full-resolution photos, so decode smaller with cacheWidth first, then tune the limits.

open as a page

In Flutter 3.47, how do you control a variable font's weight and other axes, and what did Flutter 3.41 change about FontWeight?

level: middleimportance: nice to knowfreq 18%

basics

~10 s

Declare the variable file once in pubspec, then set axes with TextStyle.fontVariations such as FontVariation.width(90). Since Flutter 3.41, fontWeight also sets the wght axis and accepts any value from 1 to 1000.

open as a page

In Flutter, what do asset transformers declared in pubspec.yaml do, and how would you add one to shrink bundled JSON question packs?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

An asset transformer is a Dart command-line package the flutter tool runs on an asset while bundling it, writing a transformed file under the same key. Declare it per asset with path: and transformers: in pubspec.yaml, and add the package as a dev dependency.

open as a page

In Flutter, how does an ImageProvider's cache key decide whether two images share one decoded copy, and where do keys go wrong?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

ImageCache reuses a decoded image whenever two providers produce equal keys from obtainKey. NetworkImage compares URL, scale and headers; FileImage only the path; MemoryImage the exact Uint8List instance, which is where most key bugs start.

open as a page