watchFile method

Future<String?> watchFile(
  1. String filePath,
  2. void callback(
    1. FileChange
    )
)

Watch a file for changes.

Implementation

Future<String?> watchFile(
  String filePath,
  void Function(FileChange) callback,
) async {
  final file = File(filePath);
  if (!file.existsSync()) return null;

  final parent = file.parent;
  final fileName = file.uri.pathSegments.last;
  final id = 'watch_${_nextId++}';

  try {
    final stream = parent.watch(events: FileSystemEvent.all);
    final sub = stream.listen((event) {
      if (!event.path.endsWith(fileName)) return;
      _handleEvent(id, event, callback);
    });

    _subscriptions[id] = WatchSubscription._(
      id: id,
      path: filePath,
      subscription: sub,
    );

    return id;
  } catch (_) {
    return null;
  }
}