add method

Future<void> add(
  1. String path, {
  2. bool recursive = false,
})

Adds path to the watch list.

path may be a file or a directory. If path is a directory, all direct children are watched (non-recursive by default). Pass recursive as true to watch subdirectories as well.

Throws WatcherError if:

  • The watcher has been closed.
  • path does not exist.
  • path is already being watched.
await watcher.add('/var/log');
await watcher.add('/etc/hosts');
await watcher.add('/srv/data', recursive: true);

Implementation

Future<void> add(String path, {bool recursive = false}) async {
  if (_closed) throw const WatcherError('Watcher is closed');

  final resolved = p.canonicalize(path);

  if (_subs.containsKey(resolved)) {
    throw WatcherError('Already watching path', path: resolved);
  }

  final type = FileSystemEntity.typeSync(resolved, followLinks: true);
  if (type == FileSystemEntityType.notFound) {
    throw WatcherError('No such file or directory', path: resolved);
  }

  // dart:io exposes watch() on Directory and File, not a standalone class.
  final Stream<FileSystemEvent> watchStream;
  if (type == FileSystemEntityType.directory) {
    watchStream = Directory(resolved).watch(recursive: recursive);
  } else {
    // Files don't support the recursive flag.
    watchStream = File(resolved).watch();
  }

  final sub = watchStream.listen(
    (fse) => _dispatch(fse),
    onError: (Object err) {
      _errorController.add(WatcherError(err.toString(), path: resolved));
    },
    cancelOnError: false,
  );

  _subs[resolved] = sub;
}