Skip to main content
1

Delete Operations

deleteIfExistsSafe()
Future<bool>
This method first checks for the file’s existence using exists() before attempting to call delete(). It is designed to be a non-crashing wrapper for file cleanup.
final file = File('path/to/temp.log');
final success = await file.deleteIfExistsSafe();

print('Deletion status: $success'); // true or false
2

Read and Access

readAsJsonSafe()
Future<Map<String, dynamic>?>
A non-crashing wrapper for reading and parsing JSON files.It handles three common failure modes gracefully:
  1. File does not exist.
  2. File exists but cannot be read (e.g., permission error).
  3. File content is not valid JSON.
final configFile = File('config.json');
final config = await configFile.readAsJsonSafe();

if (config != null) {
    print('API Key: ${config['apiKey']}'); //  Output: API Key: jsonContent
}
readAsBytesSafe()
Future<Uint8List?>
A safe wrapper around readAsBytes() that handles file existence and read errors gracefully. It is suitable for loading image or audio data.
Avoid calling this on the main thread for very large files.
final imageBytes = await File('photo.jpg').readAsBytesSafe();

if (imageBytes != null) {
    // Use the bytes to create an Image.memory widget
}
3

Getters

lengthSyncSafe
int
A robust wrapper around lengthSync(), preventing crashes if the file is deleted or becomes inaccessible between checks.
// Safe to call inside a loop or initialization code
final size = File('temp.log').lengthSyncSafe;

if (size > 1000) {
    print('File is big.');
}
lastModifiedSyncSafe
DateTime?
Safely gets the file’s synchronous last modified timestamp without throwing an exception.
final lastChange = File('cache.json').lastModifiedSyncSafe;

if (lastChange.year == 1970) {
    print('Could not determine modification date.');
}
4

Comparators

isSameFile()
bool
Checks if two File objects point to the same file location on the filesystem.
final fileA = File('data.txt');
final fileB = File('./data.txt').absolute;

print(fileA.isSameFile(fileB)); // Likely true