This tutorial shows you how to check whether a file, directory, or filesystem exists in Dart.
If you create an application using Dart, there are several ways to check whether a file, directory, or filesystem link exists or not. Below are the examples which also work in any Dart framework including Flutter. For the examples below, you don't need to add an additional dependency. You only need to add import 'dart:io';
in the file where you add the code.
Check if a File Exists
To check whether a file with the given path exists, you can create a File
object by passing the path as the constructor argument, then call the exists
method. It returns a Future
of bool
.
Future<bool> _checkFileExists(String path) {
return File(path).exists();
}
There is also a method named existsSync
that performs the checking synchronously.
bool _checkFileExistsSync(String path) {
return File(path).existsSync();
}
Check if a Directory Exists
For checking the existence of a directory, create a Directory
object with the path as the constructor argument, then call the exists
method. The method returns a Future
of bool
.
Future<bool> _checkDirectoryExists(String path) {
return Directory(path).exists();
}
It also has the synchronous version existsSync
.
bool _checkDirectoryExistsSync(String path) {
return Directory(path).existsSync();
}
Check if a Filesystem Link Exists
If you want to check whether a filesystem link exists, you can create a Link
object and call the exists
method.
Future<bool> _checkFilesystemLinkExists(String path) {
return Link(path).exists();
}
Below is the synchronous version.
bool _checkFilesystemLinkExistsSync(String path) {
return Link(path).existsSync();
}
Check if a FileSystemEntity
Exists
Actually, all of the types above are subtypes of FileSystemEntity
. If you want to perform a checking that returns true if the given path resolves to an existing file, directory, or filesystem link, you can call FileSystemEntity.type
method by passing the path to be checked. The method returns a Future
of FileSystemEntityType
. If it's not found, the type will be FileSystemEntityType.notFound
Therefore, if you only want to check the existence of a path regardless of the entity type, you can use the code below.
Future<bool> _checkFileSystemEntityExists(String path) async {
final type = await FileSystemEntity.type(path);
return type != FileSystemEntityType.notFound;
}
If you only want to return true if the file type is either a file or a directory but not a filesystem link, you can change the code above to:
Future<bool> _checkFileSystemEntityExists(String path) async {
final type = await FileSystemEntity.type(path);
return type == FileSystemEntityType.file || type == FileSystemEntityType.directory;
}
There's also a method named typeSync
that synchronously finds the type of the object that the path points to.
bool _checkFileSystemEntityExistsSync(String path) {
final type = FileSystemEntity.typeSync(path);
return type != FileSystemEntityType.notFound;
}
Flutter Code Example
Below is the full code of a simple Flutter application where you can input a path and check whether the path points to an existing file, directory, or filesystem link.
import 'dart:io';
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Woolha.com Flutter Tutorial',
home: CheckPathExistsExample(),
);
}
}
class CheckPathExistsExample extends StatefulWidget {
const CheckPathExistsExample({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _CheckPathExistsExampleState();
}
}
class _CheckPathExistsExampleState extends State<CheckPathExistsExample> {
final TextEditingController _textEditingController = TextEditingController();
bool? _result;
Future<bool> _checkFileExists(String path) {
return File(path).exists();
}
Future<bool> _checkDirectoryExists(String path) {
return Directory(path).exists();
}
Future<bool> _checkFilesystemLinkExists(String path) {
return Link(path).exists();
}
Future<bool> _checkFileSystemEntityExists(String path) async {
final type = await FileSystemEntity.type(path);
return type != FileSystemEntityType.notFound;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Woolha.com Flutter Tutorial'),
backgroundColor: Colors.teal,
),
body: Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
controller: _textEditingController,
decoration: const InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
hintText: 'Enter path',
),
),
OutlinedButton(
onPressed: () async {
final result = await _checkFileExists(_textEditingController.text);
setState(() { _result = result; });
},
child: const Text('Check file exists', style: TextStyle(color: Colors.teal)),
),
OutlinedButton(
onPressed: () async {
final result = await _checkDirectoryExists(_textEditingController.text);
setState(() { _result = result; });
},
child: const Text('Check directory exists', style: TextStyle(color: Colors.teal)),
),
OutlinedButton(
onPressed: () async {
final result = await _checkFilesystemLinkExists(_textEditingController.text);
setState(() { _result = result; });
},
child: const Text('Check link exists', style: TextStyle(color: Colors.teal)),
),
OutlinedButton(
onPressed: () async {
final result = await _checkFileSystemEntityExists(_textEditingController.text);
setState(() { _result = result; });
},
child: const Text('Check file system entity exists', style: TextStyle(color: Colors.teal)),
),
Text('Result: ${_result ?? '-'}', style: const TextStyle(color: Colors.teal)),
],
),
),
);
}
}
Summary
That's how to check the existence of a file, directory, or filesystem link in Dart. It's possible to check the existence of a specific object type, or you can also check that any entity exists in a given path.
You can also read about: