Learn/Local Storage/File Storage

File Storage

Read and write files on the device for logs, exports, and cached data

6 min~7 min read+35 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Finding the Right Directory
  2. 2. Reading and Writing Text Files
  3. 3. Saving and Loading JSON Data
  4. 4. File Strategy And Retention
  5. 5. This Lesson In Simple Words
  6. 6. Your level focus
  7. 7. One practical habit
  8. 8. Deep Understanding Guide
  9. 9. Why this lesson matters
  10. 10. Study flow for better retention
  11. 11. Quick Glossary
  12. 12. Architecture Lens

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

File Storage

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.

Finding the Right Directory

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.

dart
1// pubspec.yaml: path_provider: ^2.1.0
2import 'dart:io';
3import 'package:path_provider/path_provider.dart';
4
5// Get platform-specific directories
6Future<void> showDirectories() async {
7 // Persistent storage for user files (backed up on iOS)
8 final docsDir = await getApplicationDocumentsDirectory();
9 print('Documents: ${docsDir.path}');
10
11 // Temporary cache (OS may delete when space is low)
12 final tempDir = await getTemporaryDirectory();
13 print('Temp: ${tempDir.path}');
14
15 // App-internal files (not visible to user)
16 final supportDir = await getApplicationSupportDirectory();
17 print('Support: ${supportDir.path}');
18}

Reading and Writing Text Files

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.

dart
1// Write a text file
2Future<File> writeTextFile(String filename, String content) async {
3 final dir = await getApplicationDocumentsDirectory();
4 final file = File('${dir.path}/$filename');
5 return file.writeAsString(content);
6}
7
8// Read a text file
9Future<String> readTextFile(String filename) async {
10 final dir = await getApplicationDocumentsDirectory();
11 final file = File('${dir.path}/$filename');
12
13 if (await file.exists()) {
14 return file.readAsString();
15 }
16 return ''; // file does not exist
17}
18
19// Delete a file
20Future<void> deleteFile(String filename) async {
21 final dir = await getApplicationDocumentsDirectory();
22 final file = File('${dir.path}/$filename');
23
24 if (await file.exists()) {
25 await file.delete();
26 }
27}
28
29// Check if file exists
30Future<bool> fileExists(String filename) async {
31 final dir = await getApplicationDocumentsDirectory();
32 final file = File('${dir.path}/$filename');
33 return file.exists();
34}

Saving and Loading JSON Data

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.

dart
1import 'dart:convert';
2
3// Save a list of users as JSON file
4Future<void> cacheUsers(List<User> users) async {
5 final dir = await getApplicationDocumentsDirectory();
6 final file = File('${dir.path}/users_cache.json');
7
8 final jsonList = users.map((u) => u.toJson()).toList();
9 final jsonString = jsonEncode(jsonList);
10
11 await file.writeAsString(jsonString);
12}
13
14// Load cached users from JSON file
15Future<List<User>> loadCachedUsers() async {
16 final dir = await getApplicationDocumentsDirectory();
17 final file = File('${dir.path}/users_cache.json');
18
19 if (!await file.exists()) return [];
20
21 final jsonString = await file.readAsString();
22 final List<dynamic> jsonList = jsonDecode(jsonString);
23
24 return jsonList.map((json) => User.fromJson(json)).toList();
25}
26
27// Export data as CSV
28Future<File> exportToCsv(List<User> users) async {
29 final dir = await getApplicationDocumentsDirectory();
30 final file = File('${dir.path}/users_export.csv');
31
32 final buffer = StringBuffer();
33 buffer.writeln('Name,Email,Score');
34 for (final user in users) {
35 buffer.writeln('${user.name},${user.email},${user.score}');
36 }
37
38 return file.writeAsString(buffer.toString());
39}

When to Use File Storage

💡 When to Use File Storage

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.

Always Check if File Exists

⚠️ Always Check if File Exists

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 Strategy And Retention

File storage becomes messy without retention rules. Define policy early:

  • Decide which files are cache (replaceable) versus user-generated (must keep).
  • Keep file naming deterministic, for example user_<id>export<timestamp>.csv.
  • Add cleanup jobs for old cache files to avoid silent storage growth.
  • Store only metadata paths in your database, not full binary payloads.

This approach keeps storage predictable and avoids support issues caused by unexplained disk usage.

File Handling Edge Cases

  • Read is requested while write is still in progress for the same file.
  • Directory permission changes or storage is temporarily unavailable.
  • User deletes exported file outside your app and then tries to reopen it.
  • App is killed during write, leaving a partially written file.
  • CSV export needs escaping for commas and line breaks in text fields.

File Storage QA Checklist

  • Create, read, update, and delete file flows all work on real devices.
  • Missing file paths fail gracefully with user-friendly recovery options.
  • Large file writes remain responsive and avoid UI freezes.
  • Cache cleanup removes only temporary files, never user documents.
  • Exported files can be reopened and parsed correctly after app restart.

This Lesson In Simple Words

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.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Always model loading, success, empty, and error states before hooking the UI.

Deep Understanding Guide

Why this lesson matters

Most production bugs happen at data boundaries: slow networks, bad payloads, and error states.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Treat every network call as unreliable and design graceful fallback behavior.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Triggering API calls inside build methods and causing duplicate requests.
  • Assuming response fields always exist without null checks or parsing safeguards.
  • Displaying backend errors directly to users without safe messaging.
  • Skipping retry and offline handling for key user actions.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Implement one repository with timeout, retry, and typed parsing.
  • Add pull-to-refresh and compare stale vs fresh data behavior.
  • Create a clear UI state for empty list and network failure cases.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What package provides platform-specific directory paths in Flutter?".

Quick Glossary

  • provider: A dependency and state sharing pattern in widget trees.
  • async: Code that runs over time without blocking the UI thread.
  • future: A single asynchronous result delivered later.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

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.

Lesson Completion Checklist

  • I can explain "File Storage" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Triggering API calls inside build methods and causing duplicate requests.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

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.

What is the difference between the documents directory and the temporary directory?

The documents directory stores persistent user files. The temporary directory is for cache files that the operating system may delete when storage runs low.

How do you write text content to a file in Dart?

File.writeAsString() writes a string to the file asynchronously. Use writeAsBytes() for binary data like images.

What should you always do before reading a file?

Reading a non-existent file throws a FileSystemException. Always check file.exists() first and handle the case where the file is missing.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

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