Dart FileSystemModifyEvent
最后修改于 2025 年 4 月 4 日
Dart 中的 FileSystemModifyEvent 类表示文件系统修改事件。它是 dart:html 库的一部分,用于 Web 应用程序。
当被监控目录中的文件或目录被修改时,会触发此事件。它提供了有关文件系统所发生更改的详细信息。
基本定义
FileSystemModifyEvent 是一个用于文件系统更改的事件对象。它扩展了 Event,并包含有关已修改条目的信息。
关键属性包括用于更改文件路径的 path 和用于修改类型的 type(创建、修改或删除)。
FileSystemModifyEvent 的基本用法
此示例显示了如何监听文件系统修改事件。
main.dart
import 'dart:html';
void main() {
DirectoryEntry dir;
window.requestFileSystem(1024 * 1024).then((fs) {
dir = fs.root;
dir.onChange.listen((FileSystemModifyEvent event) {
print('Change detected in: ${event.path}');
print('Change type: ${event.type}');
});
});
}
我们请求文件系统并在根目录上设置事件监听器。当文件系统发生任何修改时,监听器会打印详细信息。
$ dart main.dart Change detected in: /example.txt Change type: modify
过滤特定事件类型
此示例演示了如何过滤特定修改类型。
main.dart
import 'dart:html';
void main() {
DirectoryEntry dir;
window.requestFileSystem(1024 * 1024).then((fs) {
dir = fs.root;
dir.onChange.listen((FileSystemModifyEvent event) {
if (event.type == 'create') {
print('New file created: ${event.path}');
} else if (event.type == 'delete') {
print('File deleted: ${event.path}');
}
});
});
}
我们过滤事件以仅处理文件创建和删除。这有助于专注于特定更改,同时忽略修改等其他更改。
$ dart main.dart New file created: /test.txt File deleted: /old.txt
监控特定文件
此示例展示了如何仅监视特定文件的更改。
main.dart
import 'dart:html';
void main() {
DirectoryEntry dir;
const targetFile = '/config.json';
window.requestFileSystem(1024 * 1024).then((fs) {
dir = fs.root;
dir.onChange.listen((FileSystemModifyEvent event) {
if (event.path == targetFile) {
print('Config file changed: ${event.type}');
// Reload config or take appropriate action
}
});
});
}
我们将事件路径与我们的目标文件路径进行比较。这创建了一个集中的监视器,它只响应指定配置文件中的更改。
$ dart main.dart Config file changed: modify
处理多个更改
此示例演示了如何处理单个事件中的多个更改。
main.dart
import 'dart:html';
void main() {
DirectoryEntry dir;
window.requestFileSystem(1024 * 1024).then((fs) {
dir = fs.root;
dir.onChange.listen((FileSystemModifyEvent event) {
print('Batch changes detected:');
event.changes.forEach((change) {
print(' ${change.path} - ${change.type}');
});
});
});
}
某些实现可能会将多个更改批处理到一个事件中。我们遍历事件中的所有更改,以单独处理每次修改。
$ dart main.dart Batch changes detected: /file1.txt - modify /temp/file2.txt - create
文件监控中的错误处理
此示例为文件系统监控添加了错误处理。
main.dart
import 'dart:html';
void main() {
DirectoryEntry dir;
window.requestFileSystem(1024 * 1024).then((fs) {
dir = fs.root;
var subscription = dir.onChange.listen(
(FileSystemModifyEvent event) {
print('Change: ${event.path}');
},
onError: (e) => print('Error: $e'),
cancelOnError: false
);
// Later: subscription.cancel();
}).catchError((e) => print('Filesystem error: $e'));
}
我们为文件系统请求和事件监听都添加了错误处理程序。当不再需要监控时,可以稍后取消订阅。
$ dart main.dart
Change: /update.txt
Error: FileSystemError {code: 5, name: "InvalidModificationError"}
最佳实践
- 特定路径: 过滤事件以仅监视相关文件
- 错误处理: 始终实现错误处理程序
- 资源清理: 完成后取消订阅
- 性能: 避免在事件处理程序中进行繁重处理
- 批量处理: 为每个事件的多个更改做好准备
来源
本教程通过实际示例介绍了 Dart 的 FileSystemModifyEvent 类,展示了基本用法、过滤、错误处理和监控技术。
作者
列出 所有 Dart 教程。