⚡ TL;DR
Master Flutter file manipulation — permission management, directory handling, and practical read-write scenarios to elevate your app's file handling.

File manipulation is a common task in many Flutter applications. Whether you need to store user data, cache files, or read and write configuration files, having a good understanding of file manipulation in Flutter is crucial. In this blog post, we will explore best practices and provide step-by-step guidance on enhancing file manipulation in Flutter. We will cover various aspects such as dependencies, requesting permission, determining the directory path, getting the reference to the file, writing to a file, and reading from a file. So, let’s dive in!
Dependencies
To begin with, let’s make sure we have the necessary dependencies in our Flutter project. Open your pubspec.yaml file and add the following dependencies:
dependencies:
flutter:
sdk: flutter
path_provider: ^2.1.5
permission_handler: ^11.3.1The path_provider package provides a platform-agnostic way to access commonly used locations on the file system, such as temporary and application-specific directories. The permission_handler package allows us to request runtime permissions when we genuinely need to access shared storage (it is not needed for app-private directories, as we’ll see below).
After adding the dependencies, don’t forget to run flutter pub get to fetch the packages.
Requesting Permission (Only When You Actually Need It)
Here’s an important correction to how this article was originally written: if you’re writing to directories provided by path_provider — getApplicationDocumentsDirectory(), getTemporaryDirectory(), or the application support directory — you don’t need any permission at all. These directories are private to your app, and the OS grants access automatically. Calling Permission.storage.request() for app-documents files is a misapplication of the API and just adds a pointless dialog for your users.
Runtime permissions only matter when you access shared storage:
- Reading photos/videos the user picked or that live in the media store requires
Permission.photos(iOS) or, on Android 13+ (API 33), the granular media permissions — declareREAD_MEDIA_IMAGES(orREAD_MEDIA_VIDEO/READ_MEDIA_AUDIO) inAndroidManifest.xmland request the matchingPermission.photos/Permission.videos/Permission.audioat runtime. On Android 12 and below,Permission.storagestill applies. - Writing to shared locations outside app directories (rare on modern Android) uses the Storage Access Framework or MediaStore rather than raw filesystem paths.
So when do you need permission_handler code? For the media-gallery case, like this:
import 'package:permission_handler/permission_handler.dart';
// Request access to the user's photos (Android 13+ READ_MEDIA_IMAGES, iOS photo library)
Future<bool> requestPhotosPermission() async {
final status = await Permission.photos.request();
if (status.isGranted) {
return true;
} else if (status.isPermanentlyDenied) {
await openAppSettings(); // Send the user to Settings to re-enable
return false;
}
return false;
}Make sure to call it only when the user interacts with a feature that touches shared media — not before every app-private file read or write.
Determining the Directory Path
Next, we need to determine the directory path where we want to read from or write to. The path_provider package provides a convenient way to retrieve the path for various directories. Add the following code to get the directory path:
import 'package:path_provider/path_provider.dart';
// Get the directory path
Future<String> getDirectoryPath() async {
Directory directory = await getApplicationDocumentsDirectory();
return directory.path;
}The getApplicationDocumentsDirectory() function returns the directory specific to the current platform where the app can store files that are private to the application. You can explore other directory types provided by the package based on your specific requirements.
Getting the Reference to the File
Once we have the directory path, we can get a reference to the file we want to read from or write to. Here are a few examples:
Writing to A File with writeAsBytes
To write data to a file as bytes, use the writeAsBytes method. Here’s an example:
import 'dart:io';
Future<void> writeToBytes(File file) async {
List<int> bytes = [72, 101, 108, 108, 111]; // "Hello" in ASCII
await file.writeAsBytes(bytes);
}In this example, we create a File object pointing to a file named example.txt in the directory path. We then write the byte data [72, 101, 108, 108, 111] to the file using the writeAsBytes method.
Writing to A File with writeAsString
To write data to a file as a string, use the writeAsString method. Here’s an example:
import 'dart:io';
Future<void> writeToString(File file) async {
String data = 'Hello, World!';
await file.writeAsString(data);
}In this example, we create a File object pointing to the same example.txt file, but this time we write the string ‘Hello, World!’ using the writeAsString method.
Reading A File with readAsString
To read data from a file as a string, use the readAsString method. Here’s an example:
import 'dart:io';
Future<void> readAsString(File file) async {
String data = await file.readAsString();
print(data);
}In this example, we read the content of the example.txt file using the readAsString method and print it to the console.
Reading A File with readAsBytes
To read data from a file as bytes, use the readAsBytes method. Here’s an example:
import 'dart:io';
Future<void> readAsBytes(File file) async {
List<int> bytes = await file.readAsBytes();
print(bytes);
}In this example, we read the content of the example.txt file as byte data using the readAsBytes method and print it to the console.
Reading A File with readAsLines
To read data from a file line by line, use the readAsLines method. Here’s an example:
import 'dart:io';
Future<void> readAsLines(File file) async {
List<String> lines = await file.readAsLines();
for (String line in lines) {
print(line);
}
}In this example, we read the content of the example.txt file line by line using the readAsLines method and print each line to the console.
Handling Errors
File I/O fails in the real world — the disk can be full, the file may not exist, or the platform may deny access. Since dart:io file methods throw FileSystemException (and async code surfaces errors through futures), wrap operations in try/catch and give the caller a meaningful result instead of crashing:
import 'dart:io';
Future<String?> readFileSafely(String path) async {
try {
final file = File(path);
if (!await file.exists()) {
return null; // Nothing saved yet — not an error
}
return await file.readAsString();
} on FileSystemException catch (e) {
// e.path, e.osError?.code and e.message tell you what went wrong
print('Failed to read file: ${e.message} (${e.path})');
return null;
} catch (e) {
print('Unexpected error reading file: $e');
return null;
}
}The same pattern applies to writes:
import 'dart:io';
Future<bool> writeFileSafely(String path, String contents) async {
try {
final file = File(path);
await file.parent.create(recursive: true); // Make sure the directory exists
await file.writeAsString(contents, flush: true);
return true;
} on FileSystemException catch (e) {
print('Failed to write file: ${e.message} (${e.path})');
return false;
}
}Note the flush: true argument — without it, writeAsString buffers in the OS and data can be lost if the app is killed immediately after.
Full Code
Here’s the full code combining all the examples above:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(const MyFileManipulationApp());
}
class MyFileManipulationApp extends StatefulWidget {
const MyFileManipulationApp({super.key});
State<MyFileManipulationApp> createState() => _MyFileManipulationAppState();
}
class _MyFileManipulationAppState extends State<MyFileManipulationApp> {
Widget build(BuildContext context) {
return MaterialApp(
title: 'File Manipulation Example',
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('File Manipulation Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: const Text('Write and Read File with Bytes'),
onPressed: () {
writeAndReadFileBytes();
},
),
ElevatedButton(
child: const Text('Write and Read File with String'),
onPressed: () {
writeAndReadFileString();
},
),
ElevatedButton(
child: const Text('Write and Read File with Lines'),
onPressed: () {
writeAndReadFileLines();
},
),
],
),
),
),
);
}
Future<void> writeToBytes(File file) async {
List<int> bytes = [72, 101, 108, 108, 111]; // "Hello" in ASCII
await file.writeAsBytes(bytes);
}
Future<void> writeToString(File file) async {
String data = 'Hello, World!';
await file.writeAsString(data);
}
Future<void> writeToLines(File file) async {
String data = 'Hello\nWorld\nflutter';
await file.writeAsString(data);
}
Future<void> writeAndReadFileBytes() async {
try {
String directoryPath = await getDirectoryPath();
File fileBytes = File('$directoryPath/exampleBytes.txt');
await writeToBytes(fileBytes);
// Reading A File with readAsBytes
await readAsBytes(fileBytes);
} on FileSystemException catch (e) {
print('File operation failed: ${e.message} (${e.path})');
}
}
Future<void> writeAndReadFileString() async {
try {
String directoryPath = await getDirectoryPath();
File fileString = File('$directoryPath/exampleString.txt');
await writeToString(fileString);
// Reading A File with readAsString
await readAsString(fileString);
} on FileSystemException catch (e) {
print('File operation failed: ${e.message} (${e.path})');
}
}
Future<void> writeAndReadFileLines() async {
try {
String directoryPath = await getDirectoryPath();
File fileLines = File('$directoryPath/exampleLines.txt');
await writeToLines(fileLines);
// Reading A File with readAsLines
await readAsLines(fileLines);
} on FileSystemException catch (e) {
print('File operation failed: ${e.message} (${e.path})');
}
}
Future<void> readAsLines(File file) async {
List<String> lines = await file.readAsLines();
for (String line in lines) {
print(line);
}
}
Future<void> readAsString(File file) async {
String data = await file.readAsString();
print(data);
}
Future<void> readAsBytes(File file) async {
List<int> bytes = await file.readAsBytes();
print(bytes);
}
Future<String> getDirectoryPath() async {
Directory directory = await getApplicationDocumentsDirectory();
return directory.path;
}
}Conclusion
In this blog post, we explored best practices for enhancing file manipulation in Flutter. We covered important aspects such as dependencies, when permissions are actually required (spoiler: not for app-documents directories), determining the directory path, getting a reference to the file, performing various file operations like writing and reading, and handling I/O errors gracefully. By following these practices and examples, you can effectively handle file manipulation in your Flutter applications.
You can find the full source code and examples discussed in this blog post on our GitHub repository. Feel free to clone or fork the repository to use it as a reference or as a starting point for your own projects.
Remember to handle exceptions and errors appropriately when dealing with file operations to ensure a robust and reliable user experience — the try/catch patterns above are a good starting point. Happy coding!
Related Posts
- Flutter Debug Banner Removal: Best Practices and Techniques
- How to Show Automatic Internet Connection Offline Message in Flutter
- A Comprehensive Guide to Flutter Buttons: Choosing the Right One for Your App
- How to Change minSdkVersion in Flutter: 2 Simple Approaches
References
- pub.dev: path_provider
- pub.dev: permission_handler
- File class — Dart API docs (dart:io)
- getApplicationDocumentsDirectory — path_provider API docs
- Android Storage Access Framework — Android developer docs
FAQ
Do I need storage permissions to write files in Flutter?
No, not for app-private directories. Writing to locations returned by path_provider — such as the application documents directory or temporary directory — requires no runtime permission because those directories belong to your app. Storage permissions are only needed when accessing shared storage, for example reading the user’s photos or videos through the media gallery.
How do I read and write a file in Flutter?
Add the path_provider package to locate a writable directory, then use Dart’s File class from dart:io. Get the directory path with getApplicationDocumentsDirectory, create a File with the full path, and call writeAsString or writeAsBytes to save data. Read it back with readAsString, readAsBytes, or readAsLines, wrapping calls in try/catch to handle failures.
What is the path_provider package used for in Flutter?
path_provider provides a platform-agnostic API for finding standard file-system locations on Android, iOS, and desktop, such as the application documents directory, temporary cache directory, and application support directory. It returns Directory objects whose paths you combine with file names. Using it keeps file code identical across platforms instead of hardcoding platform-specific storage paths.
How do I handle file errors in Flutter?
Wrap file operations in try/catch blocks and catch FileSystemException, which dart:io throws for failures such as a missing file, full disk, or denied access. Check file.exists() before reading so a missing file counts as empty rather than an error, create parent directories before writing, and pass flush: true so buffered data is not lost on an app kill.

Written by Mihir Pipermitwala
Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.
More about Mihir →