Sub topic 3
Loading Images, Text, and JSON at Runtime
This chapter covers how a running Flutter app reads the assets you declared in pubspec.yaml. It assumes you can write basic Dart, build a simple widget tree, edit pubspec.yaml and run flutter pub get, and keep YAML indentation correct. It also assumes you have already declared assets, as covered in the previous chapter.
The two entry points
Flutter gives you two ways to read a bundled asset:
Image.assetis a widget. It loads an image, decodes it, and paints it. Use it whenever the asset is a picture.rootBundleis anAssetBundleobject. It returns the raw bytes or text of any asset. Use it for JSON, plain text, binary data, and anything else that is not displayed directly as an image.
Both address an asset by its asset key. The key is the path exactly as it appears in pubspec.yaml, relative to the project root, for example assets/images/logo.png. There is no leading slash and no package: prefix for your own app's assets.
Declaring what the code will load
The examples in this chapter use this declaration:
flutter:
assets:
- assets/images/
- assets/data/config.jsonTwo rules from the declaration step matter at load time:
- A directory entry ending in
/includes the files directly inside that directory. It does not include files in subdirectories. If you keepassets/images/icons/home.png, you need to listassets/images/icons/separately. - A file entry includes exactly that file.
If the key you pass to the loader is not covered by one of these entries, the load fails at runtime. The app still compiles, because the asset list is not checked against your Dart code.
Loading an image with Image.asset
Image.asset takes the asset key as its first argument. You can also size and fit the image:
import 'package:flutter/material.dart';
class Logo extends StatelessWidget {
const Logo({super.key});
@override
Widget build(BuildContext context) {
return Image.asset(
'assets/images/logo.png',
width: 120,
fit: BoxFit.contain,
);
}
}A few details are worth knowing.
- Loading is asynchronous, but you do not write any async code. The widget asks an
ImageProviderto resolve the asset, and it paints once the image is decoded. Images are cached in Flutter'sImageCacheby key, so showing the same asset in many places does not decode it many times. - Size matters for memory. If you give only
width, the height follows the image's aspect ratio. The full-size image is still decoded into memory unless you also setcacheWidthorcacheHeight. Those parameters ask the decoder to produce a smaller bitmap, which saves memory for large source images shown in small boxes. - Failure is visible through
errorBuilder. If the asset cannot be found or decoded,Image.assetthrows during image resolution and, by default, logs the error. You can show a fallback instead:
import 'package:flutter/material.dart';
class SafeLogo extends StatelessWidget {
const SafeLogo({super.key});
@override
Widget build(BuildContext context) {
return Image.asset(
'assets/images/logo.png',
width: 120,
errorBuilder: (context, error, stackTrace) {
return const Icon(Icons.broken_image, size: 120);
},
);
}
}During development, errorBuilder helps you notice a bad path. In production code, make sure it does not hide a real packaging mistake from you.
Using an asset image with other widgets
Image.asset is a convenience for Image(image: AssetImage(...)). Use AssetImage directly when an API expects an ImageProvider rather than a widget. Examples are DecorationImage, CircleAvatar.backgroundImage, and precacheImage.
import 'package:flutter/material.dart';
class Avatar extends StatelessWidget {
const Avatar({super.key});
@override
Widget build(BuildContext context) {
return const CircleAvatar(
radius: 40,
backgroundImage: AssetImage('assets/images/logo.png'),
);
}
}AssetImage also takes part in resolution-aware selection, which the next chapter covers. For now, remember that your code names one path, and Flutter may pick a variant of that file.
Loading text and JSON with rootBundle
rootBundle is a global AssetBundle that holds everything declared in pubspec.yaml. It has two main methods:
| Method | Returns | Use for |
|---|---|---|
| `loadString(key)` | `Future<String>` | Text, JSON, CSV, Markdown, and similar |
| `load(key)` | `Future<ByteData>` | Binary data such as audio, models, or custom formats |
loadString decodes the bytes as UTF-8. If your file uses another encoding, call load and decode the bytes yourself.
Reading a JSON file
Suppose assets/data/config.json contains:
{
"appName": "Demo",
"maxItems": 20,
"features": ["search", "share"]
}You read it by loading the text and then parsing it with dart:convert:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
Future<Map<String, dynamic>> loadConfig() async {
final text = await rootBundle.loadString('assets/data/config.json');
return jsonDecode(text) as Map<String, dynamic>;
}
class Logo extends StatelessWidget {
const Logo({super.key});
@override
Widget build(BuildContext context) {
return Image.asset('assets/images/logo.png', width: 120);
}
}Note the import: rootBundle lives in package:flutter/services.dart. The show rootBundle clause keeps the rest of that library out of your namespace, which is optional but tidy.
jsonDecode returns dynamic. The cast as Map<String, dynamic> assumes the top level of the file is a JSON object. If the file's top level is an array, the cast throws a TypeError. Match the cast to the real shape of your data.
Turning JSON into a typed model
Passing Map<String, dynamic> around the app invites typos in key names. A small model class gives you one place to handle the structure:
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
class AppConfig {
const AppConfig({
required this.appName,
required this.maxItems,
required this.features,
});
final String appName;
final int maxItems;
final List<String> features;
factory AppConfig.fromJson(Map<String, dynamic> json) {
return AppConfig(
appName: json['appName'] as String,
maxItems: json['maxItems'] as int,
features: (json['features'] as List<dynamic>).cast<String>(),
);
}
static Future<AppConfig> load() async {
final text = await rootBundle.loadString('assets/data/config.json');
return AppConfig.fromJson(jsonDecode(text) as Map<String, dynamic>);
}
}If a key is missing or has the wrong type, the cast fails with a clear TypeError at the line that names the key. That is easier to debug than a null that surfaces three widgets later.
Using loaded data in the widget tree
build methods must be synchronous, so you cannot await inside them. The standard tool for showing the result of a Future is FutureBuilder.
import 'package:flutter/material.dart';
import 'app_config.dart';
class ConfigScreen extends StatefulWidget {
const ConfigScreen({super.key});
@override
State<ConfigScreen> createState() => _ConfigScreenState();
}
class _ConfigScreenState extends State<ConfigScreen> {
late final Future<AppConfig> _config = AppConfig.load();
@override
Widget build(BuildContext context) {
return FutureBuilder<AppConfig>(
future: _config,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Could not load config: ${snapshot.error}');
}
if (!snapshot.hasData) {
return const CircularProgressIndicator();
}
final config = snapshot.data!;
return Text('${config.appName}: ${config.features.join(', ')}');
},
);
}
}The code assumes AppConfig from the previous example is saved in app_config.dart.
The key detail is late final Future<AppConfig> _config = AppConfig.load();. The future is created once, when the state object first reads the field. If you wrote future: AppConfig.load() directly inside build, every rebuild would start a new load and the builder would flicker back to the loading state.
Where the data flow goes
The diagram shows the path from the declaration to the screen.
Loading once versus loading often
rootBundle caches nothing for text by default in the sense that matters here: each call to loadString returns a new String. In a release build the bytes come from the packaged bundle each time. For a small config file this cost is negligible. For a large JSON file, load it once and keep the parsed result.
Common patterns for keeping the result:
- Store the
Futurein aStatefield, as shown above, when only one screen needs it. - Load before
runAppwhen the whole app needs the data. CallWidgetsFlutterBinding.ensureInitialized()first, becauserootBundleneeds the Flutter binding. - Hold the data in whatever state management you already use.
import 'package:flutter/material.dart';
import 'app_config.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final config = await AppConfig.load();
runApp(MaterialApp(
home: Scaffold(body: Center(child: Text(config.appName))),
));
}Loading before runApp delays the first frame by the load time. That is fine for a few kilobytes. For anything large, show a splash first and load afterward.
Parsing large JSON off the main thread
jsonDecode runs on the thread that calls it. A multi-megabyte file can cause dropped frames if parsed on the UI isolate. Flutter's compute function runs a top-level function on a separate isolate:
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart' show rootBundle;
List<dynamic> _parseList(String text) => jsonDecode(text) as List<dynamic>;
Future<List<dynamic>> loadBigList() async {
final text = await rootBundle.loadString('assets/data/items.json');
return compute(_parseList, text);
}The function passed to compute must be top-level or static, and the argument and result must be sendable between isolates. Strings, lists, and maps of those are. Do this only when profiling shows a problem, because copying data between isolates has its own cost.
rootBundle.loadString itself also has a built-in parse hook through AssetBundle.loadStructuredData, which takes a parser function. It is useful when you want the bundle to cache the parsed value for you. In that case the parsed object is cached by key, so do not mutate it.
Loading assets without a BuildContext
rootBundle needs no BuildContext, which makes it convenient in services and tests. The trade-off is that it ignores any DefaultAssetBundle placed above your widget in the tree. Widgets that should be testable with a fake bundle can use:
import 'package:flutter/material.dart';
Future<String> loadGreeting(BuildContext context) {
return DefaultAssetBundle.of(context).loadString('assets/data/greeting.txt');
}By default DefaultAssetBundle.of(context) returns rootBundle. In a test you can wrap the widget in a DefaultAssetBundle that supplies a custom bundle, so the test does not depend on real files. Use rootBundle in plain Dart code and DefaultAssetBundle.of(context) inside widgets when you want that flexibility.
Common errors
The failures below all occur at runtime, after a clean compile.
| Symptom | Likely cause | Fix |
|---|---|---|
| `Unable to load asset: "assets/data/config.json"` | The file is not declared, the path is misspelled, or the directory entry does not cover a subfolder | Check the key against `pubspec.yaml` character by character |
| The error appears only after you add a new file | The running app has the old bundle | Stop the app and run it again. Hot reload does not repackage assets, and hot restart may not either |
| `TypeError: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'` | The JSON top level is an array, but the code casts to a map | Cast to the real top-level type |
| `FormatException` from `jsonDecode` | Invalid JSON, such as a trailing comma or a byte-order mark | Validate the file with a JSON linter |
| Image shows the `errorBuilder` fallback or a red error box | Wrong key, undeclared file, or corrupt image | Check the key, then open the file outside Flutter |
| Works in debug, fails in release | The path differs in case, for example `Logo.png` versus `logo.png`, and your development file system ignores case | Match the case exactly. Android's packaged assets are case-sensitive |
Here is that check as code:
import 'package:flutter/services.dart';
Future<void> printAssetKeys() async {
final manifest = await AssetManifest.loadFromAssetBundle(rootBundle);
for (final key in manifest.listAssets()) {
print(key);
}
}Use it as a temporary debugging aid. If a key you expect is missing from the list, the problem is in pubspec.yaml, not in the Dart code.
Edge cases to keep in mind
- File names with spaces or special characters. Flutter handles them, but they make keys harder to type and to read in YAML. Prefer lowercase names with underscores.
- Assets are read-only. You cannot write to
rootBundle. To save data, use a file in the app's documents directory (through a package such aspath_provider) and, if you need defaults, copy a bundled asset there on first run. - Web builds. Assets are fetched over HTTP from the app's
assets/path, so a load can fail from network errors, not only from missing files. Handle the error state in yourFutureBuilder. - Vector images. SVG is not supported by
Image.asset. Use a package such asflutter_svg, or convert the file to PNG. The loading rules for the file itself still follow this chapter. - Animated formats.
Image.assetplays animated GIF and WebP files, which can use a lot of memory. Check the frame count before bundling.
Putting it together
The following app declares the assets from the YAML at the top of this chapter, loads the config, and shows the logo. It combines the pieces above and is runnable once the three files exist.
import 'package:flutter/material.dart';
import 'app_config.dart';
void main() => runApp(const DemoApp());
class DemoApp extends StatelessWidget {
const DemoApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: HomePage());
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late final Future<AppConfig> _config = AppConfig.load();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Assets')),
body: Center(
child: FutureBuilder<AppConfig>(
future: _config,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (!snapshot.hasData) {
return const CircularProgressIndicator();
}
final config = snapshot.data!;
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset('assets/images/logo.png', width: 120),
const SizedBox(height: 16),
Text(config.appName),
Text('Max items: ${config.maxItems}'),
],
);
},
),
),
);
}
}Required files: assets/images/logo.png, assets/data/config.json with the JSON shown earlier, and lib/app_config.dart with the AppConfig class.
Summary of decisions
- Use
Image.assetorAssetImagefor pictures, androotBundlefor everything else. - Pass the asset key exactly as declared, with no leading slash.
- Create a
Futureonce, not insidebuild. - Parse into typed models so shape errors fail early.
- Reach for
computeonly when a large parse shows up in profiling. - Restart the app fully after changing the asset list.
Exercise
Your app calls FutureBuilder(future: rootBundle.loadString('assets/data/config.json'), ...) directly inside build. The text reloads and the spinner flashes every time the parent rebuilds. Why does this happen, and how do you fix it?
Show answer
Each rebuild calls loadString again, which creates a new Future. FutureBuilder sees a different future object and restarts in the waiting state. Create the future once, for example in a late final field of a State class or in initState, and pass that stored future to FutureBuilder.
Exercise
You add assets/data/regions/europe.json to the project and declare only assets/data/ in pubspec.yaml. rootBundle.loadString('assets/data/regions/europe.json') throws "Unable to load asset". What is wrong, and what are two ways to fix it?
Show answer
A directory entry covers only the files directly inside it, not subdirectories. Either add assets/data/regions/ as its own entry, or declare the single file assets/data/regions/europe.json. After editing pubspec.yaml, stop and rerun the app so the bundle is rebuilt.
Exercise
A JSON asset has an array at its top level. Your code does jsonDecode(text) as Map<String, dynamic> and throws a TypeError. Write the corrected line for a list of maps.
Show answer
final items = (jsonDecode(text) as List<dynamic>).cast<Map<String, dynamic>>(); The top-level value is a list, so cast it to List<dynamic> first, then cast each element to the map type.