Introduction to File Handling in Dart
Dart provides the dart:io library for file system operations. Using this library, you can read from and write to files, create directories, list files, and more. File operations are typically asynchronous, ensuring your application remains responsive. This guide covers the essential file handling techniques you'll need in Dart and Flutter applications.
Important Notes
The dart:io library is not available on web platforms. If you're building a Flutter web app, you'll need alternative approaches (like using the browser's file APIs or a server). For command‑line Dart or Flutter for mobile/desktop, dart:io works perfectly.
Reading a File
The simplest way to read a file is using readAsString() or readAsLines(). These methods are asynchronous and return a Future.
Reading a File Line by Line (Stream)
For large files, you should read and process them line by line using a Stream. This avoids loading the whole file into memory.
Writing to a File
Use writeAsString() to write data to a file. By default, this overwrites the file if it exists. You can use the mode parameter to append instead.
Appending to a File
You can also open the file in append mode and write using a sink, which is more efficient for multiple writes.
Checking if a File Exists
Deleting a File
Working with Paths
Dart's File class uses system paths. For cross‑platform path handling (like joining directories), you can use the path package (add path: ^1.8.0 to your pubspec.yaml).
Error Handling
Always handle exceptions when working with files. Common errors include file not found, permission denied, and disk full.
Working with Directories
You can create, list, and delete directories using the Directory class.
Key Takeaways
- Use
dart:iofor file operations (not available on web).
- Use
- Asynchronous methods (
readAsString,writeAsString) are recommended.
- Asynchronous methods (
- For large files, process line by line with streams.
- Always handle exceptions with try/catch.
- Use the
pathpackage for cross‑platform path manipulation.
- Use the
- Check file existence before reading to avoid errors.