Rules / Style / prefer-async-await

prefer-async-await

lint/style/prefer-async-await
recommended
Same as prefer-async-await · Dart Code Metrics

Flags .then(...) future chains that should use async/await.

Chaining callbacks with Future.then nests logic inside closures and scatters error handling across onError/catchError, whereas async/await lets asynchronous code read top-to-bottom with ordinary try/catch. The rule walks statement and expression trees looking for any method call named then, reporting each one; it treats function-literal arguments as opaque and does not descend into lambda bodies. Matching is purely syntactic on the then name, so it does not confirm the receiver is actually a Future.

Invalid

example.dartdart
// Bad: using .then() chains instead of async/await
Future<String> getData() {
  return fetch().then((data) {
    return process(data);
  });
}

void processUser() {
  getUserId().then((id) {
    print(id);
  });
}

Future<int> compute() {
  return loadData().then((d) => transform(d)).catchError((e) {
    print('Error: $e');
    return 0;
  });
}

class Api {
  Future<String> fetchName() {
    return http.get(url).then((response) => response.body);
  }
}

void refresh() {
  reload().then((_) => notifyListeners());
}
Prefer async/await over .then() chains
2Future<String> getData() {
3 return fetch().then((data) {
Prefer async/await over .then() chains
8void processUser() {
9 getUserId().then((id) {
Prefer async/await over .then() chains
14Future<int> compute() {
15 return loadData().then((d) => transform(d)).catchError((e) {
Prefer async/await over .then() chains
22 Future<String> fetchName() {
23 return http.get(url).then((response) => response.body);
Prefer async/await over .then() chains
27void refresh() {
28 reload().then((_) => notifyListeners());

Valid

example.dartdart
// Good: using async/await instead of .then() chains
Future<String> getData() async {
  final data = await fetch();
  return process(data);
}

void processUser() async {
  final id = await getUserId();
  print(id);
}

Future<int> compute() async {
  try {
    final d = await loadData();
    return transform(d);
  } catch (e) {
    print('Error: $e');
    return 0;
  }
}

class Api {
  Future<String> fetchName() async {
    final response = await http.get(url);
    return response.body;
  }
}

// OK: .then() with simple arrow function
Future<String> simpleFetch() => fetch().then((d) => d);

How to configure

Set the severity of prefer-async-await in your falcon.json:

falcon.jsonjson
{
  "linter": {
    "rules": {
      "style": {
        "prefer-async-await": "error"
      }
    }
  }
}