unawaited_futures
Future
结果在 async
函数体中必须使用 await
等待,或使用 dart:async
标记为 unawaited
。
详情
#应该在 async 函数体内部等待返回 Future
的函数。
在 async 方法中很容易忘记 await,因为命名约定通常不会告诉我们一个方法是同步还是异步(dart:io
中的一些方法除外)。
当您真的想要启动一个 fire-and-forget Future
时,推荐的方法是使用 dart:async
中的 unawaited
。// ignore
和 // ignore_for_file
注释也有效。
错误
dart
void main() async {
doSomething(); // Likely a bug.
}
正确
dart
Future doSomething() => ...;
void main() async {
await doSomething();
unawaited(doSomething()); // Explicitly-ignored fire-and-forget.
}
启用
#要启用 unawaited_futures
规则,请在您的 analysis_options.yaml
文件中的 linter > rules 下添加 unawaited_futures
analysis_options.yaml
yaml
linter:
rules:
- unawaited_futures
如果您改为使用 YAML 映射语法来配置 linter 规则,请在 linter > rules 下添加 unawaited_futures: true
analysis_options.yaml
yaml
linter:
rules:
unawaited_futures: true
除非另有说明,否则本网站上的文档反映的是 Dart 3.7.1 版本。页面上次更新于 2025-03-07。 查看源代码 或 报告问题。