What package provides platform-specific directory paths in Flutter?
The path_provider package gives you functions like getApplicationDocumentsDirectory() that return the correct folder path for each platform.
Read and write files on the device for logs, exports, and cached data
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
Having trouble? AI is here to help
Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.
Use the AI button at the bottom of the screen
Sometimes you need to work directly with files on the device rather than using a database or key-value store. Common use cases include saving downloaded images or documents, exporting data as CSV or JSON files, writing log files for debugging, caching large API responses to disk, and reading user-selected files from the device. Flutter provides the path_provider package to find the correct directories on each platform, and Dart's built-in dart:io library handles the actual file reading and writing.
Every platform has specific folders for different types of files. The path_provider package abstracts away the platform differences so you always get the correct path. The documents directory is for user-generated content that should persist. The temporary directory is for cache files that the OS can delete when storage runs low. The application support directory is for app-internal files that users should not see.
1// pubspec.yaml: path_provider: ^2.1.02import 'dart:io';3import 'package:path_provider/path_provider.dart';45// Get platform-specific directories6Future<void> showDirectories() async {7// Persistent storage for user files (backed up on iOS)8final docsDir = await getApplicationDocumentsDirectory();9print('Documents: ${docsDir.path}');1011// Temporary cache (OS may delete when space is low)12final tempDir = await getTemporaryDirectory();13print('Temp: ${tempDir.path}');1415// App-internal files (not visible to user)16final supportDir = await getApplicationSupportDirectory();17print('Support: ${supportDir.path}');18}
Once you have the directory path, you create a File object pointing to a specific filename. The File class from dart:io provides methods like writeAsString, readAsString, writeAsBytes, and readAsBytes for working with the file contents. All file operations are asynchronous and return Futures.
1// Write a text file2Future<File> writeTextFile(String filename, String content) async {3final dir = await getApplicationDocumentsDirectory();4final file = File('${dir.path}/$filename');5return file.writeAsString(content);6}78// Read a text file9Future<String> readTextFile(String filename) async {10final dir = await getApplicationDocumentsDirectory();11final file = File('${dir.path}/$filename');1213if (await file.exists()) {14return file.readAsString();15}16return ''; // file does not exist17}1819// Delete a file20Future<void> deleteFile(String filename) async {21final dir = await getApplicationDocumentsDirectory();22final file = File('${dir.path}/$filename');2324if (await file.exists()) {25await file.delete();26}27}2829// Check if file exists30Future<bool> fileExists(String filename) async {31final dir = await getApplicationDocumentsDirectory();32final file = File('${dir.path}/$filename');33return file.exists();34}
A very common pattern is to cache API responses as JSON files so the app can show data even when offline. You serialize your model objects to JSON, write the string to a file, and read it back when needed.
1import 'dart:convert';23// Save a list of users as JSON file4Future<void> cacheUsers(List<User> users) async {5final dir = await getApplicationDocumentsDirectory();6final file = File('${dir.path}/users_cache.json');78final jsonList = users.map((u) => u.toJson()).toList();9final jsonString = jsonEncode(jsonList);1011await file.writeAsString(jsonString);12}1314// Load cached users from JSON file15Future<List<User>> loadCachedUsers() async {16final dir = await getApplicationDocumentsDirectory();17final file = File('${dir.path}/users_cache.json');1819if (!await file.exists()) return [];2021final jsonString = await file.readAsString();22final List<dynamic> jsonList = jsonDecode(jsonString);2324return jsonList.map((json) => User.fromJson(json)).toList();25}2627// Export data as CSV28Future<File> exportToCsv(List<User> users) async {29final dir = await getApplicationDocumentsDirectory();30final file = File('${dir.path}/users_export.csv');3132final buffer = StringBuffer();33buffer.writeln('Name,Email,Score');34for (final user in users) {35buffer.writeln('${user.name},${user.email},${user.score}');36}3738return file.writeAsString(buffer.toString());39}
Use file storage for large data like images, PDFs, CSV exports, or JSON cache files. For small settings use SharedPreferences, for structured queries use SQLite, and for fast object storage use Hive.
Before reading a file, always check if it exists using file.exists(). Attempting to read a non-existent file throws a FileSystemException that will crash your app if not caught.
File storage becomes messy without retention rules. Define policy early:
This approach keeps storage predictable and avoids support issues caused by unexplained disk usage.
Read and write files on the device for logs, exports, and cached data. Networking lessons teach your app how to request, store, and display remote data safely.
Think in architecture, reliability, and team-level maintainability.
Always model loading, success, empty, and error states before hooking the UI.
Most production bugs happen at data boundaries: slow networks, bad payloads, and error states.
Repository and service boundaries keep networking logic testable and replaceable.
As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.
The path_provider package gives you functions like getApplicationDocumentsDirectory() that return the correct folder path for each platform.
The documents directory stores persistent user files. The temporary directory is for cache files that the operating system may delete when storage runs low.
File.writeAsString() writes a string to the file asynchronously. Use writeAsBytes() for binary data like images.
Reading a non-existent file throws a FileSystemException. Always check file.exists() first and handle the case where the file is missing.
Something seems incorrect, unclear, or missing? Let us know.
FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.
Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.
Sign in to continue with exercises and quiz for this lesson.
Sign In to Continue