File Handling in Dart
In this lesson, you will learn how to work with files in Dart. File handling allows Dart applications to read data from files, write data to files, and manage local storage effectively.
File operations are commonly used in configuration files, logs, reports, and command-line applications.
Why File Handling Is Important
Real-world applications frequently need to:
- Store user data locally
- Read configuration settings
- Write logs and reports
- Process text and data files
Dart provides file handling through the dart:io library.
Importing the File Library
To work with files, you must import the dart:io package.
import 'dart:io';
Creating a File Object
A File object represents a file stored on your system.
Example: Creating a file object for a sales report.
File reportFile = File('sales_report.txt');
Writing Data to a File
Let’s store daily sales data in a file.
File reportFile = File('sales_report.txt');
reportFile.writeAsStringSync(
'Total Sales: 1500\nOrders: 45\nProfit: 320'
);
This code creates the file if it does not exist and writes text into it.
Appending Data to a File
Sometimes you may want to add new data instead of replacing existing content.
reportFile.writeAsStringSync(
'\nNew Order: 120',
mode: FileMode.append
);
This is useful for logging activities.
Reading Data from a File
To read the contents of a file:
String content = reportFile.readAsStringSync();
print(content);
This prints all the data stored in the file.
Reading Files Line by Line
Reading line-by-line is helpful for processing large files.
List<String> lines = reportFile.readAsLinesSync();
for (var line in lines) {
print(line);
}
Checking If a File Exists
Always check if a file exists before reading it.
if (reportFile.existsSync()) {
print('File exists');
} else {
print('File not found');
}
Deleting a File
Files can be deleted when they are no longer needed.
if (reportFile.existsSync()) {
reportFile.deleteSync();
print('File deleted');
}
Handling File Errors Safely
File operations may fail due to permission issues or missing files. Use exception handling for safety.
try {
String data = reportFile.readAsStringSync();
print(data);
} catch (e) {
print('Error reading file');
}
Real-World Example: User Data File
Let’s save and read a user profile.
File userFile = File('user.txt');
userFile.writeAsStringSync('Name: Alex\nAge: 28\nCity: Austin');
String userData = userFile.readAsStringSync();
print(userData);
Best Practices for File Handling
- Always check file existence
- Use exception handling
- Close resources when required
- Avoid blocking operations in UI apps
📝 Practice Exercises
Exercise 1
Create a file and write three lines of text.
Exercise 2
Read the file content and print it line by line.
Exercise 3
Append new data to the file.
✅ Practice Answers
Answer 1
File file = File('data.txt');
file.writeAsStringSync('Line 1\nLine 2\nLine 3');
Answer 2
List<String> lines = file.readAsLinesSync();
lines.forEach(print);
Answer 3
file.writeAsStringSync('\nLine 4', mode: FileMode.append);
What’s Next?
In the next lesson, you will learn about Packages and Imports in Dart, which allow you to reuse code and build scalable applications.