Sub topic 1
What Counts as an Asset and How Flutter Bundles It
Prerequisites
You should be comfortable with these before starting:
- Basic Dart syntax, including
asyncandawait. - Building a simple widget tree with
MaterialApp,Scaffold, andText. - Editing
pubspec.yamland runningflutter pub get. - YAML indentation rules, where spaces define structure.
What counts as an asset
An asset is a file your app ships with and reads at runtime. Common examples are images, JSON or text data, and fonts. Flutter does not read these files from your project folder on the user's device. Instead, the build tool copies each declared asset into the app bundle, which is the package that gets installed.
Flutter only bundles files you list. A file that exists in your project but is not declared is missing from the app, and loading it fails at runtime.
How bundling works
Declaring files and folders in pubspec.yaml
Declare assets under the flutter: key. You can list single files or whole folders. A folder entry must end with a slash.
flutter:
assets:
- assets/images/
- assets/data/config.jsonThis line bundles every file directly inside assets/images/, and it bundles the one file assets/data/config.json. Subfolders are not included by a folder entry, so list them separately.
Loading images, text, and JSON at runtime
Use Image.asset for images. Use rootBundle.loadString for text and JSON. Both take the exact path you declared.
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);
}
}The path is case-sensitive and must match the file name exactly. A typo causes an error at runtime, not at build time.
Exercise
Exercise
You declare assets/images/ in pubspec.yaml and place a file at assets/images/icons/star.png. Will Image.asset('assets/images/icons/star.png') work? Explain why.
Show answer
No. A folder entry includes only the files directly inside that folder. The file in the icons subfolder is not bundled. Add assets/images/icons/ as its own entry, then run flutter pub get and restart the app.