Skip to the workspace
Pebellslearn by building
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.

flutter / Other File Types

Explore each scene at your own pace.

01 · The rule

The rule

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.