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.