Sub topic 5
Reading and Writing Files
This chapter assumes you know Dart's Future, async and await, can add packages in pubspec.yaml, and have read the earlier chapters on serialization and path_provider. Here you will write and read files that hold app data. You will also see how to make those writes safe against crashes and bad input.
When a file is the right tool
A file suits data that is read and written as a whole, such as a JSON export, a cached API response, a downloaded image or a small document. It does not suit data you need to search, filter or update one record at a time. For that, use a database.
Files in Flutter come from dart:io. This library does not exist on Flutter web, so code that uses File will not compile for a web target. If you plan to support web, keep file code behind an interface (see the repository chapter).
The Note model and the file helpers
The examples reuse the Note model from the serialization chapter. toMap turns a note into a map of plain values, and fromMap rebuilds it.
class Note {
const Note({this.id, required this.title, this.body});
final int? id;
final String title;
final String? body;
Map<String, Object?> toMap() => {
'id': id,
'title': title,
'body': body,
};
factory Note.fromMap(Map<String, Object?> map) => Note(
id: map['id'] as int?,
title: map['title'] as String,
body: map['body'] as String?,
);
}The file code asks path_provider for the documents directory and builds a File inside it. Then it saves a list of notes as one JSON array and loads it back.
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
Future<File> _notesFile() async {
final dir = await getApplicationDocumentsDirectory();
return File('${dir.path}/notes.json');
}
Future<void> saveNotes(List<Note> notes) async {
final file = await _notesFile();
final json = jsonEncode(notes.map((n) => n.toMap()).toList());
await file.writeAsString(json);
}
Future<List<Note>> loadNotes() async {
final file = await _notesFile();
if (!await file.exists()) return [];
final decoded = jsonDecode(await file.readAsString()) as List<dynamic>;
return decoded
.map((e) => Note.fromMap(e as Map<String, Object?>))
.toList();
}Three points about this code:
loadNotesreturns an empty list when the file is missing. On first launch the file does not exist yet, and that is normal, not an error.jsonEncodeaccepts only numbers, strings, booleans,null, lists and maps with string keys. This is whytoMapreturns plain values. ADateTimewould throw, so convert it to a string first, for example withtoIso8601String().jsonDecodereturnsdynamic, so the casts matter. A cast that does not match the data throws aTypeError.
The data flow
Choosing a directory
path_provider returns different directories for different purposes. Pick the one that matches how long the data should live.
| Function | Typical use | Cleared by the system? |
|---|---|---|
| `getApplicationDocumentsDirectory()` | Data the user would be upset to lose | No, removed only when the app is uninstalled |
| `getApplicationSupportDirectory()` | App-owned files the user should not see | No |
| `getTemporaryDirectory()` | Caches and scratch files | Yes, at any time |
Use the temporary directory only for data you can rebuild. If a user's notes sit in a cache folder, the operating system may delete them to free space.
Reading and writing in different ways
File offers several methods. Choose by the size of the data and how you want to process it.
writeAsStringandreadAsStringhandle text. They load the whole content into memory, which is fine for files up to a few megabytes.writeAsBytesandreadAsByteshandle binary data such as images.openWritereturns anIOSinkandopenReadreturns aStream<List<int>>. Use them for large files so you do not hold everything in memory.
writeAsString replaces the file's content by default. To add to the end, pass a mode:
import 'dart:io';
Future<void> appendLog(File file, String line) async {
await file.writeAsString(
'$line\n',
mode: FileMode.append,
flush: true,
);
}The flush: true argument asks the operating system to push the data to disk before the future completes. It is slower, so use it only when losing the last write would matter.
For a large text file, read it line by line:
import 'dart:convert';
import 'dart:io';
Future<int> countLines(File file) async {
var count = 0;
final lines = file
.openRead()
.transform(utf8.decoder)
.transform(const LineSplitter());
await for (final _ in lines) {
count++;
}
return count;
}Making writes safe
Partial writes
writeAsString truncates the file and then writes. If the app is killed or the device loses power in between, the file can be left empty or cut off. The next jsonDecode then throws a FormatException, and the user loses all notes.
A common fix is to write to a temporary file in the same directory and then rename it over the target. A rename on the same file system is atomic on the major platforms, so readers see either the old file or the new one.
import 'dart:convert';
import 'dart:io';
Future<void> writeJsonAtomically(File target, Object data) async {
final temp = File('${target.path}.tmp');
await temp.writeAsString(jsonEncode(data), flush: true);
await temp.rename(target.path);
}Keep the temporary file in the same directory as the target. A rename across different volumes can fail or turn into a copy, which is not atomic.
Corrupt or unexpected content
A file can hold bad data because of a partial write, a bug in an older app version, or a schema change. Decide what to do instead of letting the exception crash the screen.
Future<List<Note>> loadNotesSafely() async {
try {
return await loadNotes();
} on FormatException {
return [];
} on TypeError {
return [];
}
}Returning an empty list hides the problem, and the next save will overwrite the damaged file. If the data matters, rename the bad file to notes.json.bad first so it can be recovered or reported.
Concurrent writes
Two overlapping calls to saveNotes can interleave. Dart is single-threaded, but await lets another call start in the middle of a write. Serialize writes by chaining them, or by using one object that owns the file and queues its saves. The repository chapter shows where that object belongs.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `PathNotFoundException` when reading | The file was never written | Check `exists()` or catch the exception and return a default |
| `PathNotFoundException` when writing into a subfolder | The parent folder does not exist | Call `create(recursive: true)` on the `Directory` first |
| `Converting object to an encodable object failed` | A model field is not a JSON type, such as `DateTime` | Convert it in `toMap` |
| `type 'List<dynamic>' is not a subtype of type 'List<Note>'` | Missing `.map(...).toList()` after `jsonDecode` | Build typed objects from each element |
| Data vanishes after some weeks | File was stored in the temporary directory | Move it to the documents or support directory |
| `MissingPluginException` in a test | `path_provider` needs a real platform | Inject the directory, as shown below |
Making file code testable
Calling getApplicationDocumentsDirectory() inside every function ties your code to a real device. A simpler design takes the File as a parameter, so a test can pass a file in a temporary directory.
import 'dart:convert';
import 'dart:io';
Future<void> saveNotesTo(File file, List<Note> notes) async {
await file.parent.create(recursive: true);
final json = jsonEncode(notes.map((n) => n.toMap()).toList());
await file.writeAsString(json);
}
Future<List<Note>> loadNotesFrom(File file) async {
if (!await file.exists()) return [];
final decoded = jsonDecode(await file.readAsString()) as List<dynamic>;
return decoded
.map((e) => Note.fromMap(e as Map<String, Object?>))
.toList();
}A test can then use Directory.systemTemp.createTemp() and delete the folder afterwards:
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
void main() {
late Directory dir;
setUp(() async {
dir = await Directory.systemTemp.createTemp('notes_test');
});
tearDown(() async {
await dir.delete(recursive: true);
});
test('round-trips notes through a file', () async {
final file = File('${dir.path}/notes.json');
await saveNotesTo(file, [const Note(title: 'Milk', body: '2 litres')]);
final loaded = await loadNotesFrom(file);
expect(loaded.single.title, 'Milk');
expect(loaded.single.body, '2 litres');
});
test('returns an empty list when the file is missing', () async {
expect(await loadNotesFrom(File('${dir.path}/none.json')), isEmpty);
});
}What files do not give you
A file does not protect its content. Other apps cannot read your app's private directory on a normal device, but a rooted device or a backup can expose it. Do not put tokens or passwords in a JSON file. Use secure storage for those.
A file also has no query support. To find one note you load and decode the whole file. When the list grows to thousands of items, or you need to update single records often, move to SQLite.
Exercise
Your app saves a user's drafts with writeAsString. After a crash during saving, the draft file is empty and the user's text is gone. What change prevents this, and why does it work?
Show answer
Write the new content to a temporary file in the same directory (with flush: true), then rename it over the real file. A same-volume rename is atomic, so the file is always either the complete old version or the complete new version, never a half-written one.
Exercise
A teammate stores a cached list of search results in getApplicationDocumentsDirectory() and a list of the user's saved notes in getTemporaryDirectory(). Which choice is wrong, and where should each be stored?
Show answer
The saved notes are in the wrong place. The system may delete the temporary directory at any time. Move the notes to the documents (or support) directory. The cached search results are rebuildable, so they belong in the temporary directory.
Exercise
Why does loadNotesFrom(File file) test more easily than loadNotes()?
Show answer
It receives the file as a parameter, so a test can pass a file inside a directory made with Directory.systemTemp.createTemp(). loadNotes() calls path_provider, which needs a real platform and throws MissingPluginException in a plain unit test.