The dart:io library in Dart provides all the classes and functions needed for file, directory, and socket-based I/O operations β but itβs important to note that it works only in non-web environments (like Flutter mobile, desktop, or server-side Dart), not in the browser.
When it comes to file handling, dart:io allows us to create, read, write, and delete files in a simple and efficient way.
Hereβs how it typically works:
1. Importing the library #
To use file operations, we import:
import 'dart:io';
2. Reading a file #
You can read a file either synchronously or asynchronously.
Asynchronous (recommended):
void main() async {
final file = File('example.txt');
String contents = await file.readAsString();
print(contents);
}
This approach doesnβt block the main thread β ideal for Flutter apps.
Synchronous (blocks execution):
void main() {
final file = File('example.txt');
String contents = file.readAsStringSync();
print(contents);
}
I generally avoid synchronous operations in Flutter since it can freeze the UI if the file is large.
3. Writing to a file #
You can write text or data into a file:
void main() async {
final file = File('example.txt');
await file.writeAsString('Hello Dart I/O!');
}
You can also append data instead of overwriting:
await file.writeAsString('New line', mode: FileMode.append);
4. Checking and deleting files #
You can verify if a file exists or delete it:
if (await file.exists()) {
await file.delete();
}
5. Practical example from my experience #
I used dart:io in a Flutter desktop app to store user preferences and cache downloaded data locally.
For example, I had to write logs to a local file during error tracking:
final logFile = File('logs/error_log.txt');
await logFile.writeAsString('Error at ${DateTime.now()}\n', mode: FileMode.append);
This helped us debug issues even without network access.
Challenges faced #
One issue I faced was handling file permissions, especially on mobile platforms.
For instance, on Android, certain directories require permission through the permission_handler package.
Another challenge was path management, so I used the path_provider package to get directories like app documents or cache folders safely.
Limitations #
dart:iodoes not work in browsers β itβs meant for server-side or local filesystem apps only.- Large file operations can impact performance if done synchronously.
Alternative #
When I needed file operations in web apps, I used the dart:html library for browser-based storage or cloud storage services like Firebase Storage.
So, to summarize:
The
dart:iolibrary provides a powerful and straightforward API for interacting with files β allowing you to read, write, and manage files locally. Itβs ideal for mobile, desktop, or server apps, but not for web environments.
