async function declared void cannot be awaited
ID |
dart.correctness.avoid_void_async |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Async Misuse |
Language |
Dart |
Description
Reports an async function or method declared to return void rather than Future<void>. main is not reported, since the entry point is allowed to be void async.
Rationale
An async body always produces a future; declaring the return type void throws that future away at the signature. A caller then has nothing to await and no way to know when the work finished, so ordering silently depends on timing, and tests that call the method go on to assert against state that has not been written yet. Worse, an error raised after the first await has no future to complete with - it surfaces as an unhandled asynchronous error in the zone rather than at the call site, so a try/catch around the call catches nothing and the failure is reported far from its cause, if at all.
The following code illustrates the pattern detected by this rule:
class Repository {
// FLAGGED: async function declared void cannot be awaited
void save(String data) async {
await write(data);
}
}
Remediation
Declare the return type Future<void> and await the call, or attach a .catchError handler where the result is deliberately not awaited. Keep void only where the framework requires that exact signature, such as a callback type that is declared to return void, and in that case handle errors inside the body rather than letting them escape.