avoid-passing-async-when-sync-expected
Avoid passing asynchronous function as an argument where a synchronous function is expected.
This rule tries to prevent incorrect expectations that the passed async function will be awaited, and helps prevent tricky bugs when the same callback is executed several times (since there is no await, and the user of your app can tap the button multiple times). Consider avoiding slow async tasks in your callbacks (e.g. backend calls), and try sending events to your state management solution and then sending the request from there.
For this rule it's recommended to exclude the test
folder.
⚙️ Config
Set ignored-instances
(default is empty) to ignore instances that are expected to receive an async function.
Set ignored-invocations
(default is empty) to ignore specific invocations.
dart_code_metrics:
rules:
- avoid-passing-async-when-sync-expected:
ignored-instances:
- SomeClass
ignored-invocations:
- someFunction
Example
❌ Bad:
void doSomethingWithCallback(VoidCallback function) {
...
function();
...
}
void main() {
// LINT: Expected a sync function, but got an async one.
// Try passing a sync function or changing the parameter type.
doSomethingWithCallback(() async {
await Future.delayed(Duration(seconds: 1));
print('Hello World');
});
}
✅ Good:
void doSomethingWithCallback(VoidCallback function) {
...
function();
...
}
void main() {
doSomethingWithCallback(() {
print('Hello World');
});
}