Dart – Read File as String
To read a text file as a String in Dart, use File.readAsString() for asynchronous file reading or File.readAsStringSync() for synchronous file reading. Both methods are provided by the dart:io library and read the entire file into memory.
File.readAsString() returns a Future<String>. You can obtain the file contents with await inside an async function, or by handling the returned Future with then().
File.readAsStringSync() returns the file contents directly as a String, but it blocks program execution until the read operation finishes. For most applications, prefer readAsString() so file I/O does not unnecessarily block execution.
By default, both methods decode the file as UTF-8. If the file uses another supported text encoding, pass it through the encoding argument.
Dart readAsString() and readAsStringSync() syntax
Future<String> readAsString({Encoding encoding = utf8})
String readAsStringSync({Encoding encoding = utf8})
The asynchronous method completes with a string after the file has been read. The synchronous method returns the string immediately after the blocking read operation finishes.
Read a file as String in Dart with async and await
Using await is a concise way to work with the Future<String> returned by readAsString().
import 'dart:io';
Future<void> main() async {
final file = File('resources/file.txt');
final contents = await file.readAsString();
print(contents);
}
The File object represents the path. Calling readAsString() starts the read operation, and await gives you the resulting string when the operation completes.
Example – Read File as String
In this example, we shall read a file as string using readAsString(). We use then to handle the Future returned by File.readAsString().
Dart Program
import 'dart:io';
void main() {
File('resources/file.txt').readAsString().then((String contents) {
print('File Contents\
---------------');
print(contents);
});
}
Run the program. If reading the file is successful, we shall get contents of the file to the variable String contents. Consequently, we can access this variable.
Output
D:\software\dart-sdk\bin\dart.exe --enable-asserts --enable-vm-service:52528 C:\workspace\DartTutorial\bin\main.dart
Observatory listening on [http://127.0.0.1:52528/ugP1OacMnQw=/
File](http://127.0.0.1:52528/ugP1OacMnQw=/
File) Contents
---------------
Welcome to www\.tutorialkart.com.
Process finished with exit code 0
Example – Read File as String Synchronously
In this example, we shall read a file as string synchronously using readAsStringSync(). The program execution shall wait here at readAsStringSync() until all the contents of the File is read and returned as String.
Dart Program
import 'dart:io';
void main() {
var contents = File('resources/file.txt').readAsStringSync();
print('File Contents\
---------------');
print(contents);
}
Run the program. If reading the file is successful, we shall get contents of the file to the variable String contents.
Output
D:\software\dart-sdk\bin\dart.exe --enable-asserts --enable-vm-service:52663 C:\workspace\DartTutorial\bin\main.dart
Observatory listening on [http://127.0.0.1:52663/Hp8acRTRhIw=/
File](http://127.0.0.1:52663/Hp8acRTRhIw=/
File) Contents
---------------
Welcome to www\.tutorialkart.com.
Process finished with exit code 0
Check whether a Dart file exists before reading it
If a file path may be missing, you can call exists() before readAsString(). This is useful when a missing file is an expected condition that your program should handle explicitly.
import 'dart:io';
Future<void> main() async {
final file = File('resources/file.txt');
if (await file.exists()) {
final contents = await file.readAsString();
print(contents);
} else {
print('File not found.');
}
}
An existence check does not replace error handling when the file can change between operations or when reading can fail for another reason, such as a permissions problem.
Handle errors from File.readAsString()
A read operation can fail because the file does not exist, the path is invalid, or the process cannot access the file. Wrap the asynchronous read in try and catch when your program needs to recover from file-system errors.
import 'dart:io';
Future<void> main() async {
try {
final contents = await File('resources/file.txt').readAsString();
print(contents);
} on FileSystemException catch (e) {
print('Could not read file: ${e.message}');
}
}
Read a non-UTF-8 text file as String
readAsString() uses UTF-8 by default. When you know that a text file uses a different supported encoding, pass that encoding explicitly. For example, the following program reads a Latin-1 file.
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final contents = await File('resources/file.txt')
.readAsString(encoding: latin1);
print(contents);
}
Read a JSON file as String and decode it in Dart
A JSON file is still text, so you can first read it with readAsString() and then pass the returned string to jsonDecode().
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final jsonText = await File('resources/data.json').readAsString();
final data = jsonDecode(jsonText);
print(data);
}
Keep the file-reading step and the JSON-decoding step conceptually separate: readAsString() produces text, while jsonDecode() parses that text into Dart values.
Read a Flutter asset as String
Packaged Flutter assets are not read with a normal File path. Add the text file to the app’s asset bundle in pubspec.yaml, then load it with rootBundle.loadString() or an AssetBundle obtained from the current context.
flutter:
assets:
- assets/file.txt
import 'package:flutter/services.dart';
Future<void> loadTextAsset() async {
final contents = await rootBundle.loadString('assets/file.txt');
print(contents);
}
This distinction matters in Flutter: use an asset bundle for files packaged with the application, and use dart:io File for files that are available through the native file system. Browser-based Dart applications cannot use dart:io.
Read large text files without loading the entire file as one String
readAsString() reads the entire file before completing. For a large text file, consider openRead() so the program can process data as a stream instead of holding the complete file contents in one string.
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final lines = File('resources/large-file.txt')
.openRead()
.transform(utf8.decoder)
.transform(const LineSplitter());
await for (final line in lines) {
print(line);
}
}
Dart file paths when using readAsString()
The examples above use the relative path resources/file.txt. In a Dart command-line program, a relative file path is interpreted from the process’s current working directory. If a relative path is not finding the file you expect, print Directory.current.path or use an absolute path while diagnosing the problem.
import 'dart:io';
void main() {
print(Directory.current.path);
}
When to use readAsString(), readAsStringSync(), or openRead()
| Method | Use it when | Result |
|---|---|---|
readAsString() | You want to read a normal text file asynchronously | Future<String> |
readAsStringSync() | You specifically need a blocking synchronous read | String |
openRead() | You want to stream a large file or process it in chunks or lines | Stream<List<int>> |
rootBundle.loadString() | You are reading a text asset packaged with a Flutter app | Future<String> |
Dart file-to-String summary
Use File.readAsString() for the usual asynchronous case and File.readAsStringSync() only when blocking file I/O is appropriate. Both read the complete file as text and use UTF-8 by default. For large files, stream the contents with openRead(); for packaged Flutter assets, use the Flutter asset bundle instead of a normal file-system path.
In this Dart Tutorial, we learned how to read the contents of a file as String in Dart programming language.
TutorialKart.com