exists
- Dart course
- Intermediate
- Lesson 91/116
- 5 min
Learn to check file existence with File.exists.
Checking file existence
File.existsSync() returns a bool telling whether a file exists. Checking before reading prevents a missing file error.
Example: if (f.existsSync()) { print(f.readAsStringSync()); }. If the file exists it reads the content; otherwise it skips.
The async exists() returns a Future<bool>. For small programs the synchronous version is simpler.
Handling a missing file
If the file is missing readAsStringSync() throws. To prevent this, check with existsSync() first and use a default value when missing.
Example: var content = f.existsSync() ? f.readAsStringSync() : 'empty';. If the file is missing it returns 'empty'; the program does not crash.
This pattern is common for config files: when the file is missing a default setting is used.
Practice Print existence
Import the library with import 'dart:io';. In main create File('test.txt'); write with writeAsStringSync('data'). Print the result of existsSync() with print.
Starter code
// Import the dart:io library
void main() {
// write to test.txt, print its existence
}Sample solution
import 'dart:io';
void main() {
var f = File('test.txt');
f.writeAsStringSync('data');
print(f.existsSync());
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does existsSync() return?
- A string
- A bool Correct answer
- void
- A Future
Explanation: existsSync() returns a bool.
2 The existsSync call
var f = File('not.txt');
if (f.____()) {
print('var');
}
var f = File('not.txt');
if (f.existsSync()) {
print('var');
}
Explanation: existence is checked with existsSync().
3 Existence check parts
| Term | Meaning |
|---|---|
existsSync() |
Sync check |
exists() |
Async check |
Future<bool> |
Async return |
if (f.existsSync()) |
Condition |