Dart – Read File as String
To read File as a String in Dart, you can use File.readAsString() method or File.readAsStringSync().
File.readAsString() is an asynchronous method and returns a Future<String>. In your callback function, you get the String with contents of file.
File.readAsStringSync() is a synchronous method and returns the contents of file as a String.
Since asynchronous method does not block the execution of program, while contents of the file are fetched, File.readAsString() is preferred over File.readAsStringSync().
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\n---------------');
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 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\n---------------');
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 Contents
---------------
Welcome to www.tutorialkart.com.
Process finished with exit code 0
Conclusion
In this Dart Tutorial, we learned how to read the contents of a file as String in Dart programming language.