Other File Types
A new Sprout user should not face an empty screen. You want to ship a starter list of common houseplants, with names and watering intervals, as a JSON file inside the app. Images and fonts have special widgets; every other file is read the same general way.
The rule
Declare any file, then read it with
rootBundleandawait.
flutter:
assets:
- assets/data/[
{"name": "Fern", "every": 3},
{"name": "Cactus", "every": 14}
]import 'dart:convert';
import 'package:flutter/services.dart';
Future<List<dynamic>> loadStarterPlants() async {
final text = await rootBundle.loadString('assets/data/plants.json');
return jsonDecode(text) as List<dynamic>;
}- Declaring works exactly as for images: list the folder or file under
assets. rootBundleis the app's bundle of assets.loadStringreads a text file such as JSON, CSV or Markdown;loadreads raw bytes asByteData, for things like audio or a small database file.- Both return a
Future, because reading is not instant. Youawaitit inside anasyncfunction, and that function returns aFuturetoo. jsonDecodefromdart:convertturns the text into Dart lists and maps.
Inside widgets you may also see DefaultAssetBundle.of(context).loadString(...), which does the same job but lets tests swap in a fake bundle.
The shortcut
For any non-image asset, run the same four-beat chain: declare, load, await, decode.
Declare
- assets/data/underflutter: assets:inpubspec.yaml, then rerun the app.
The trap is forgetting await. Then text is a Future<String>, not a String, and jsonDecode(text) will not compile.
Drills
Answer fast — trust the rule.
Which call reads a bundled JSON file as text?
What type does rootBundle.loadString(path) return?
Which function turns JSON text into Dart lists and maps?
A sound file for a "watered" chime is bundled. How is it read?
Remember
- Declare any file, then read it with
rootBundleandawait. - Four beats: declare, load, await, decode.
- Trap: a missing
awaitleaves you holding a Future, not the text.
