跳到主要內容

unawaited_futures

穩定
提供修復

async 函式主體中的 Future 結果必須使用 dart:async 進行 await 或標記為 unawaited

詳細資訊

#

應該在 async 函式主體中 await 返回 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