Sub topic 4
Finding the right directory with path_provider
This chapter assumes you know Dart async code (Future, async, await), can add a package to pubspec.yaml, and have seen the Note model with toMap and fromMap from the previous chapter. Here you learn where an app may write files on each platform, how path_provider finds those places, and which mistakes cause lost data.
Why directories matter
A mobile app runs in a sandbox. The operating system gives each app its own private area and blocks access to other apps' files. You cannot hard-code a path such as /data/user/0/com.example.app/files, because the real path differs between Android, iOS, macOS, Windows and Linux, and it can change between app installs or OS updates.
The path_provider package asks the platform for these locations. It returns a Directory, and you build file paths from it. Where you write matters for four reasons:
- Backup: some locations are included in device backups and others are not.
- Eviction: the OS may delete cache directories when storage runs low, without warning.
- Visibility: some locations are visible to the user in a file manager and others are private to the app.
- Permissions: private locations need no permission prompt. Shared locations often do.
Setup
Add the package from the command line:
flutter pub add path_provider pathThe path package is optional but useful. It joins path segments with the correct separator for the current platform.
path_provider does not work on the web, because a browser has no app file system. Calling it there throws an UnsupportedError. If your app targets the web, guard calls with kIsWeb from package:flutter/foundation.dart, or use a storage option designed for browsers.
The main directory functions
| Function | Typical use | Backed up? | OS may delete it? |
|---|---|---|---|
| `getApplicationDocumentsDirectory()` | User data the app cannot recreate | Yes (iOS, and Android if backup is enabled) | No |
| `getApplicationSupportDirectory()` | App data that is not user-facing, such as an index or state file | Yes on iOS, depending on platform settings | No |
| `getTemporaryDirectory()` | Downloads and scratch files | No | Yes |
| `getApplicationCacheDirectory()` | Data you can re-download or recompute | No | Possibly |
| `getExternalStorageDirectory()` | App-specific area on shared storage (Android only) | No | Removed on uninstall |
| `getDownloadsDirectory()` | User's downloads folder (desktop) | Not applicable | No |
Behavior is platform specific, so check the package documentation for the platforms you ship. Two rules cover most decisions:
- If losing the file would hurt the user, use documents or support.
- If you can rebuild the file, use cache or temporary.
What each function maps to
On Android, getApplicationDocumentsDirectory() maps to the app's app_flutter directory inside internal storage. On iOS and macOS it maps to the Documents directory of the app container. The platform decides the exact string, so treat it as opaque.
The documents directory on iOS can be exposed to the user through the Files app if you set UIFileSharingEnabled in Info.plist. Do not put internal files such as databases or indexes there unless you want users to see them. Use the support directory for those.
Worked example: a small path helper
This example resolves each directory once and builds a path inside a subfolder. It creates the subfolder if it is missing.
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
Future<File> appFile(String name, {String folder = 'data'}) async {
final base = await getApplicationSupportDirectory();
final dir = Directory(p.join(base.path, folder));
if (!await dir.exists()) {
await dir.create(recursive: true);
}
return File(p.join(dir.path, name));
}
Future<void> printLocations() async {
final docs = await getApplicationDocumentsDirectory();
final support = await getApplicationSupportDirectory();
final temp = await getTemporaryDirectory();
print('documents: ${docs.path}');
print('support: ${support.path}');
print('temp: ${temp.path}');
}Call printLocations() once on each target platform. Seeing the real values makes the differences concrete.
create(recursive: true) creates missing parent folders too, and it does not fail if the folder already exists. The exists() check is therefore optional here, but it makes the intent clear.
Using the directory with the Note model
The earlier saveNotes and loadNotes functions used getApplicationDocumentsDirectory(). That works. A better choice for an app-internal JSON file that the user does not browse is the support directory. The only change is the directory call:
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
Future<File> notesFile() async {
final dir = await getApplicationSupportDirectory();
await dir.create(recursive: true);
return File(p.join(dir.path, 'notes.json'));
}
Future<bool> notesFileExists() async {
final file = await notesFile();
return file.exists();
}
Future<void> deleteNotesFile() async {
final file = await notesFile();
if (await file.exists()) {
await file.delete();
}
}The calls to saveNotes and loadNotes can then use notesFile() instead of building the path themselves. This keeps the path decision in one place.
Resolving paths once
Each get...Directory() call crosses from Dart into native code through a platform channel. The call is asynchronous and usually fast, but it is not free. In a hot code path, such as a list item's build, avoid calling it repeatedly. Resolve it once and keep the result:
import 'dart:io';
import 'package:path_provider/path_provider.dart';
class AppPaths {
AppPaths._(this.support, this.cache);
final Directory support;
final Directory cache;
static Future<AppPaths> load() async {
final support = await getApplicationSupportDirectory();
final cache = await getApplicationCacheDirectory();
return AppPaths._(support, cache);
}
}Create the object during startup, after WidgetsFlutterBinding.ensureInitialized(), and pass it to the code that needs it. This also helps testing, because a test can build an AppPaths with fake directories.
import 'package:flutter/widgets.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final paths = await AppPaths.load();
runApp(MyApp(paths: paths));
}
class MyApp extends StatelessWidget {
const MyApp({super.key, required this.paths});
final AppPaths paths;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Text('Data in ${paths.support.path}'),
);
}
}Platform channels need the binding to be ready. If you call path_provider in main() before ensureInitialized(), you get an error about the binary messenger not being initialized.
How the call travels
The returned Directory is only a handle to a path. The folder may not exist yet. On some platforms the support directory is not created until you ask for it, so call create(recursive: true) before you write, as the helpers above do.
Edge cases and common errors
Treating a path as permanent
Do not save an absolute path in preferences or a database. On iOS, the app container path contains an identifier that can change after an app update or a restore from backup. A stored absolute path then points to nothing. Store only the relative part, such as photos/cover.jpg, and rebuild the full path from the current directory at read time.
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
Future<File> resolveStored(String relativePath) async {
final base = await getApplicationSupportDirectory();
return File(p.join(base.path, relativePath));
}Keeping important data in the cache
Cache and temporary directories can be emptied by the OS or by the user clearing app cache. A note stored there will vanish. Keep only reproducible data in them, such as downloaded thumbnails.
Forgetting the missing-file case
A file that has never been written does not exist. readAsString() on it throws a PathNotFoundException, a subtype of FileSystemException. Check exists() first, or catch the exception, and return a sensible default such as an empty list.
Writing the wrong platform's API
getExternalStorageDirectory() returns null on iOS and throws UnsupportedError on other unsupported platforms. Check the platform with Platform.isAndroid before you call it, and handle null.
import 'dart:io';
import 'package:path_provider/path_provider.dart';
Future<Directory?> androidExternalDir() async {
if (kIsWebSafeCheck()) return null;
if (!Platform.isAndroid) return null;
return getExternalStorageDirectory();
}
bool kIsWebSafeCheck() => false;Note that dart:io's Platform is also unavailable on the web, so on a multi-platform app check kIsWeb first. The stub above shows where that check goes. Replace it with kIsWeb from package:flutter/foundation.dart in a real app.
Not cleaning up
Files in the support or documents directory stay until you delete them. A feature that writes a new file on every export will fill the user's storage. Track what you create and delete files you no longer need, or write exports to the temporary directory.
Concurrent writes
Two writeAsString calls on the same file at the same time can interleave, and the second may truncate the first. Serialize writes through one object. For safer saves, write to a temporary file in the same folder and then rename it over the target. A rename within one volume replaces the file in a single step on most platforms.
import 'dart:io';
Future<void> safeWrite(File target, String content) async {
final tmp = File('${target.path}.tmp');
await tmp.writeAsString(content, flush: true);
await tmp.rename(target.path);
}flush: true asks the OS to push the bytes to disk before the call returns. That makes a crash right after the write less likely to leave a half-written file.
Choosing a directory quickly
Ask these questions in order:
- Can the app rebuild this data? If yes, use the cache directory.
- Is it a short-lived scratch file? Use the temporary directory.
- Does the user expect to see or share it? Use the documents directory.
- Otherwise, use the support directory.
Exercise
Your app downloads profile pictures from a server and also keeps a JSON file of the user's drafts. Which directory would you use for each, and why? What would you store in a database instead of the absolute file path of a picture?
Show answer
Put the profile pictures in the cache directory (getApplicationCacheDirectory), because the app can download them again if the OS removes them. Put the drafts file in the support directory (or documents if users should see it), because losing it would lose user work and the OS does not delete it. In a database, store only a relative path such as "pictures/42.jpg", then build the full path from the current directory at read time, because the container path can change after an update or restore.
Exercise
A teammate calls getApplicationSupportDirectory() in main() before runApp() and the app crashes at startup with an error about the binary messenger. What is missing, and where should the call go?
Show answer
WidgetsFlutterBinding.ensureInitialized() has not run yet, so platform channels are not ready. Call it first in main(), then await the directory call, then call runApp().