Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Working with Assets  ›  Capstone Project

Other File Types

Other File Types 15 minAny declared asset, such as a JSON or text file, can be read at run time through rootBundle, which returns a Future because loading is asynchronous.

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 rootBundle and await.

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.
  • rootBundle is the app's bundle of assets. loadString reads a text file such as JSON, CSV or Markdown; load reads raw bytes as ByteData, for things like audio or a small database file.
  • Both return a Future, because reading is not instant. You await it inside an async function, and that function returns a Future too.
  • jsonDecode from dart:convert turns 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.

From file to Plant listStep 1 of 4
  1. Declare

    - assets/data/ under flutter: assets: in pubspec.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.

quick drill

Which call reads a bundled JSON file as text?

quick drill

What type does rootBundle.loadString(path) return?

quick drill

Which function turns JSON text into Dart lists and maps?

quick drill

A sound file for a "watered" chime is bundled. How is it read?

Remember

  • Declare any file, then read it with rootBundle and await.
  • Four beats: declare, load, await, decode.
  • Trap: a missing await leaves you holding a Future, not the text.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainLoad the starter plants

Sprout ships assets/data/plants.json containing a list of starter plants. Write a function that reads it and returns the decoded list, and explain why the function must be async and what must be in pubspec.yaml for it to work.