Sub topic 5
Reading and Writing Files in Flutter
This chapter assumes basic Dart classes, null safety, Future, async and await, Flutter state, and adding packages with pubspec.yaml. A file is useful when your app needs to store structured data such as notes, drafts, or an export. Unlike preferences, a file can hold a larger amount of data in a format your app controls.
Find an App-Owned Directory
Do not choose an arbitrary path such as a desktop or phone path. Each platform gives an app its own directories. The path_provider package finds those directories for you.
The application documents directory is intended for data that should remain available between launches. A cache directory is intended for temporary data that the operating system may remove when storage is low.
Add these dependencies to pubspec.yaml, then run flutter pub get:
dependencies:
path_provider: ^2.1.5Serialize Models and Write JSON
Serialization means converting an object into a format that can be stored or transmitted. JSON is text, so a Note needs toMap and fromMap methods before it can be saved.
The following repository stores all notes in one file. A repository is a class or group of methods that hides storage details from the rest of the app.
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
class Note {
const Note({required this.title, this.body});
final String title;
final String? body;
Map<String, Object?> toMap() => {
'title': title,
'body': body,
};
factory Note.fromMap(Map<String, Object?> map) => Note(
title: map['title'] as String,
body: map['body'] as String?,
);
}
Future<File> notesFile() async {
final directory = await getApplicationDocumentsDirectory();
return File('${directory.path}/notes.json');
}
Future<void> saveNotes(List<Note> notes) async {
final file = await notesFile();
final data = notes.map((note) => note.toMap()).toList();
await file.writeAsString(jsonEncode(data));
}
Future<List<Note>> loadNotes() async {
final file = await notesFile();
if (!await file.exists()) {
return [];
}
final text = await file.readAsString();
final decoded = jsonDecode(text) as List<dynamic>;
return decoded
.map((item) => Note.fromMap(
Map<String, Object?>.from(item as Map),
))
.toList();
}writeAsString creates the file if it does not exist and replaces its contents if it does. readAsString is asynchronous because the operating system performs file input and output outside the Dart code’s immediate execution.
Common Errors and Safer Choices
- Always check whether a file exists before reading a first-run file.
- Treat JSON as untrusted input. A damaged or older file can cause
jsonDecodeor a type cast to fail. - Keep file operations out of
build. Calling them there can repeat the operation whenever Flutter rebuilds the widget. - Do not store passwords or authentication tokens in an ordinary JSON file. Use secure storage for secrets.
- For many records or frequent searches, a database is usually better than repeatedly rewriting one large file.
A file is a good fit for small or medium snapshots, exports, and settings that have nested structure. SQLite is a better fit when data needs filtering, sorting, relationships, or partial updates.
Exercise
What should loadNotes return when notes.json does not exist yet, and why?
Show answer
It should return an empty list because a missing file commonly means this is the app's first load, not that loading failed.