avoid-passing-async-when-sync-expected
preset: recommended
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.
note
For this rule it's recommended to exclude the test
folder.
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');
});
}