Sub topic 3
Loading Images, Text, and JSON at Runtime
This chapter assumes that you know basic Dart syntax, can build simple Flutter widget trees, and can edit pubspec.yaml. You should also understand YAML indentation.
Flutter bundles assets into the application when you declare them in pubspec.yaml. An asset is a file that ships with your app, such as an image, a text file, or a JSON configuration file. At runtime, your Dart code reads the bundled file by using the path declared in the project.
Declare the assets first
Create this project structure:
assets/
images/
logo.png
data/
config.jsonThen add the files to the flutter section of pubspec.yaml:
flutter:
assets:
- assets/images/
- assets/data/config.jsonThe directory entry includes every file in assets/images/. The individual file entry includes only config.json.
YAML uses indentation to express structure. Use spaces rather than tabs. After changing pubspec.yaml, run:
flutter pub getFlutter now knows that these files belong in the application bundle.
Display an image with `Image.asset`
Use Image.asset when the bundled file is an image that you want to display in the widget tree:
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: LogoPage()));
}
class LogoPage extends StatelessWidget {
const LogoPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Bundled image')),
body: Center(
child: Image.asset(
'assets/images/logo.png',
width: 120,
height: 120,
fit: BoxFit.contain,
),
),
);
}
}Image.asset creates a widget that loads the image from Flutter’s asset bundle. The width, height, and fit properties control its layout. BoxFit.contain keeps the complete image visible inside the specified area.
You can also provide a fallback while an image loads:
Image.asset(
'assets/images/logo.png',
errorBuilder: (context, error, stackTrace) {
return const Icon(Icons.broken_image);
},
)The errorBuilder runs when Flutter cannot load or decode the image. It is useful for a user-friendly interface, but it does not fix an incorrect asset path.
Read text with `rootBundle`
Flutter exposes the application’s bundled files through an asset bundle. The global rootBundle object can read a text file as a string.
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadWelcomeText() {
return rootBundle.loadString('assets/data/welcome.txt');
}The method returns a Future<String> because reading the file is asynchronous. A Future represents a value that will become available later.
To show the result in a widget, use FutureBuilder:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
void main() {
runApp(const MaterialApp(home: TextFilePage()));
}
class TextFilePage extends StatelessWidget {
const TextFilePage({super.key});
Future<String> loadText() {
return rootBundle.loadString('assets/data/welcome.txt');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Bundled text')),
body: FutureBuilder<String>(
future: loadText(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(child: Text('Could not load the file: ${snapshot.error}'));
}
return Padding(
padding: const EdgeInsets.all(16),
child: Text(snapshot.data ?? ''),
);
},
),
);
}
}FutureBuilder rebuilds its contents as the Future changes state. The example handles the waiting, error, and successful result states.
Decode JSON data
JSON is text with a structure for objects, arrays, strings, numbers, booleans, and null values. Use Dart’s dart:convert library to convert JSON text into Dart values.
Suppose assets/data/config.json contains:
{
"title": "Welcome",
"showTips": true,
"maxItems": 12
}Load and decode it like this:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
void main() {
runApp(const MaterialApp(home: ConfigPage()));
}
class ConfigPage extends StatelessWidget {
const ConfigPage({super.key});
Future<Map<String, dynamic>> loadConfig() async {
final text = await rootBundle.loadString('assets/data/config.json');
final decoded = jsonDecode(text);
if (decoded is! Map<String, dynamic>) {
throw const FormatException('Expected a JSON object');
}
return decoded;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('JSON configuration')),
body: FutureBuilder<Map<String, dynamic>>(
future: loadConfig(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(child: Text('Configuration error: ${snapshot.error}'));
}
final config = snapshot.data!;
final title = config['title'] as String? ?? 'Untitled';
final showTips = config['showTips'] as bool? ?? false;
final maxItems = config['maxItems'] as int? ?? 0;
return Center(
child: Text('$title: tips=$showTips, max items=$maxItems'),
);
},
),
);
}
}jsonDecode returns a dynamic value because JSON can have several shapes. Checking that the result is a map makes the expected structure explicit. The later casts read individual fields with suitable fallback values.
For larger applications, convert the map into a model class instead of passing Map<String, dynamic> through many widgets. A model centralizes validation and makes the rest of the app easier to read.
Common loading failures
| Symptom | Likely cause | Check |
|---|---|---|
| `Unable to load asset` | The path is missing or misspelled | Compare the Dart path with `pubspec.yaml` |
| The image is not displayed | The file is not a supported image or has a bad path | Open the image and inspect `errorBuilder` output |
| JSON decoding fails | The JSON syntax or expected shape is wrong | Validate the file and check `jsonDecode` |
| Old content still appears | The asset or declaration changed during development | Perform a full restart, not only a hot reload |
Hot reload keeps much of the running application state. When you add or rename an asset, use a full restart if the new file is not found.
Exercise
Why does loadConfig use both await rootBundle.loadString(...) and jsonDecode(...)?
Show answer
loadString reads the bundled JSON file as text. jsonDecode converts that text into Dart values such as maps, lists, strings, and numbers.